如何在弹出花式框>上附加带有按钮的点击事件

How to attach Click event with a button on popup fancybox>

本文关键字:按钮 事件      更新时间:2023-09-26

我无法使用包含input按钮的弹出表单附加单击事件。代码给出如下:

<a id="btnEditSummary" href=#>Edit Summary </a>
<div id="editSummary" class="hidden">
     <input type=button id="btnEdit" value="Update" />
    </div>
function openPoPup(clickHandle,contentHandle,width,height)
{
    width = typeof a !== 'undefined' ? a : 600;
    height = typeof b !== 'undefined' ? b : 300;
    $.fancybox(
        $(contentHandle).html(),
        {
            'width'             : width,
            'height'            : height,
            'minWidth'          :  width,
            'minHeight'         :  height,
            'autoScale'         : true,
            'transitionIn'      : 'none',
            'transitionOut'     : 'none',
            'hideOnContentClick': false,
            'onStart': function () {
                //On Start callback if needed
            }
        }
    );
}    
$("#btnEditSummary").click(function()
            {
                openPoPup('#btnEditSummary','#editSummary',300,300);
                $( "#btnEdit" ).on( "click", function() {
                    alert( $( this ).text() );
                });
            }
    $( "#btnEdit" ).on( "click", function() {
                    alert( $( this ).text() );
    });

方法的问题在于,您实际上是在 fancybox 中显示#editSummary选择器clone,作为参数在 openPoPup() 函数中传递,因此 click 事件绑定到文档流中的原始选择器,而不是绑定到 fancybox 内的clone

作为一种解决方法,您可以使用 fancybox onComplete回调(我假设您使用的是 v1.3.4,因为代码中的 API 选项(将 click 事件绑定到 fancybox 中的元素#btnEdit,例如:

function openPoPup(clickHandle, contentHandle, width, height) {
    width = typeof a !== 'undefined' ? a : 600;
    height = typeof b !== 'undefined' ? b : 300;
    $.fancybox($(contentHandle).html(), {
        width: width,
        height: height,
        // minWidth: width, // not valid in v1.3.x but 2.x
        // minHeight: height, // not valid in v1.3.x but 2.x
        autoScale: true,
        transitionIn: 'none',
        transitionOut: 'none',
        hideOnContentClick: false,
        onStart: function () {
            //On Start callback if needed
        },
        onComplete: function () {
            // bind click event to element inside fancybox
            $("#fancybox-content").on("click", "#btnEdit", function () {
                alert("click event bound");
            });
        }
    });
}
jQuery(document).ready(function ($) {
    $("#btnEditSummary").click(function () {
        openPoPup('#btnEditSummary', '#editSummary', 300, 300);
    });
}); // ready

请注意,我正在使用.on()的委托形式:

$("#fancybox-content").on("click", "#btnEdit", function (){ ... });

参见 JSFIDDLE