jQuery-如何使.on事件对动态创建的HTML有效? [英] jQuery - How to make .on event work for dynamically created HTML?

查看:100
本文介绍了jQuery-如何使.on事件对动态创建的HTML有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Reading up on the New specs for the newest jQuery 1.x library, it says to use .on to attach events that work for dynamically created jQuery elements, however, I can't seem to get this work at all. In my $(document).ready function I have the following:

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();时发生这种情况应用正确吗?

Ok, so this will drop down the [ Read more... ] text and turn it into a [ Collapse Information... ] string that will go underneath of the actual content that is being expanded. But when I click on the [ Collapse Information... ] text, it doesn't collapse anything, instead it goes to the top of the page, thus having an href="#", but using .on should prevent that from happening when the event.preventDefault(); is applied correct??

我正在使用jQuery库,网址为:<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Am using the jQuery library found here: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

即使这样很重要,我的HTML也会像这样布置:

My HTML is laid out like so, if this even matters:

<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>.

The first time I click it, it works, but the 2nd time, when [ Collapse Information... ] is shown it doesn't work at all. So it is not attaching itself to the dynamically created <p class="desc"><a href="#" class="dropdown" id="' + theId + '">[ Collapse Information... ]</a></p>.

为什么不呢?还有其他我应该使用的代替.on的东西吗?我知道.live自jQuery 1.7起就不再使用. .click也不起作用,因为我已经尝试过了.还有什么其他选择?

Why not? Is there something else I should be using instead of .on? I know that .live is no longer used since jQuery 1.7. .click will not work either as I have already tried that as well. What other options are there?

推荐答案

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

To get the on method to register a delegate event handler (just as the delegate method does), you need to specify a selector for the element, and apply it to an element that already exist.

例如:

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

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

Preferably, you should apply it to a parent element as close as possible to the dynamically added elements rather than "body", to reduce the scope as much as possible. Otherwise the selector ".dropdown" needs to be evaluated for every click that happens in the page. Typically you would use the containing element that you add the dynamic content to.

这篇关于jQuery-如何使.on事件对动态创建的HTML有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆