1

阅读最新 jQuery 1.x 库的新规范,它说用于.on附加适用于动态创建的 jQuery 元素的事件,但是,我似乎根本无法完成这项工作。在我的$(document).ready功能中,我有以下内容:

jQuery:

$(".dropdown").on("click", function(event) {
    event.preventDefault();
    var type = $(this).text() == '[ Read more... ]' ? 'expand' : 'collapse';
    var theDiv = type == 'expand' ? $(this).parent().next("div") : $(this).parent().prev("div");
    var theId = $(this).attr("id");
    $(this).parent().remove();
    var vText = theId == 'reqMat' ? 'Every candidate is required to submit a headshot and candidate statement.' : 'To strengthen your candidacy and let people know what you\'re all about, we invite you to create a campaign video.';

    theDiv.animate({height: 'toggle'}, 500, function(){
        if (type == 'expand')
            theDiv.after('<p class="desc"><a href="#" class="dropdown" id="' + theId + '">[ Collapse Information... ]</a></p>');
        else
            theDiv.before('<p class="desc">' + vText + ' <a href="#" class="dropdown" id="' + theId + '">[ Read more... ]</p>');

        if (theId == 'optMat' && type == 'expand')
        {
            var sVidWidth = $("#sampleVideo").width();
            $("#sampleVideo").css({'height': (sVidWidth/1.5) + 'px'});
        }
        else if (theId == 'optMat' && type == 'collapse')
        {
            var iframe = $('#sampleVideo')[0];
            var player = $f(iframe);
            player.api('pause');
        }

        if (theId == 'reqMat' && type == 'expand')
        {
            handleBullets();
        }
    });
});

好的,所以这将下拉[ Read more... ]文本并将其转换为一个[ Collapse Information... ]字符串,该字符串将位于正在扩展的实际内容的下方。但是当我单击[ Collapse Information... ]文本时,它不会折叠任何内容,而是转到页面顶部,因此有一个href="#", 但是使用.on应该可以防止在event.preventDefault();正确应用时发生这种情况?

我正在使用这里找到的 jQuery 库: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

如果这甚至很重要,我的 HTML 的布局是这样的:

<h4>Header 1</h4>
<p class="desc">Brief description. <a href="#" id="reqMat" class="dropdown">[ Read more... ]</a></p>
<div style="display: none;">
    <p>More information is in here...</p>
</div>
<h4>Header 2</h4>
<p class="desc">Brief description. <a href="#" id="optMat" class="dropdown">[ Read more... ]</a></p>
<div style="display: none;">
    <p>More information is in here...</p>
</div>

我第一次点击它,它工作,但第二次,当[ Collapse Information... ]显示它根本不起作用。所以它不会将自己附加到动态创建的<p class="desc"><a href="#" class="dropdown" id="' + theId + '">[ Collapse Information... ]</a></p>.

为什么不?还有什么我应该使用的东西来代替.on吗?我知道.live自 jQuery 1.7 以来不再使用它。 .click也不会工作,因为我也已经尝试过了。还有哪些其他选择?

4

1 回答 1

3

要让on方法注册一个委托事件处理程序(就像delegate方法一样),您需要为元素指定一个选择器,并将其应用于已经存在的元素。

例如:

$("body").on("click", ".dropdown", function(event) {

最好将其应用于尽可能靠近动态添加的元素的父元素,而不是"body",以尽可能缩小范围。否则,".dropdown"需要为页面中发生的每次点击评估选择器。通常,您将使用添加动态内容的包含元素。

于 2013-07-21T23:30:23.360 回答