简体   繁体   English

与动态div绑定jQuery

[英]jquery on binding with dynamic div

I have an issue with jquery. 我对jquery有问题。 Say i have 2 divs in jquery, 假设我在jquery中有2个div,

<div id='1'>               //static div
</div>

<div id='2'>               //dynamic div
</div>

The static div is always present in the document, but dynamic div toggle when we click over static div. 静态div始终存在于文档中,但是当我们单击静态div时,动态div会切换。 Now what i want is to place an event on dynamic div something like : 现在我想要在动态div上放置一个事件,例如:

$(document).on("show", "#2", {}, function() {
 alert("div 2 present");
});

so that i can do something when dynamic div is present in the document. 这样,当文档中存在动态div时,我就可以执行某些操作。 How can i do this ? 我怎样才能做到这一点 ?

There is no 'show' event triggered by an element when it becomes visible. 当元素变为可见时,没有由元素触发的“显示”事件。 You will have to tie the handler to the event which causes the element to become visible in the first place. 您将不得不将处理程序与事件相关联,从而使该元素首先变得可见。 In this case, that seems to be a click event on the first div: 在这种情况下,这似乎是第一个div上的click事件:

$(document).on("click", "#1", function() {
    $("#2").toggle();

    if ( $("#2").is(":visible") ) {
        alert("div 2 present");
    }
});

Note that according to the HTML 4 spec., element IDs should not start with a number. 请注意,根据HTML 4规范,元素ID不应以数字开头。 That's alright in HTML 5, however. 但是,在HTML 5中没关系。

A further improvement to note is that, when binding handlers to dynamically generated elements, it is better to target the nearest static parent element than to allow delegation to be handled at the document level; 需要注意的进一步改进是,在将处理程序绑定到动态生成的元素时,最好将最近的静态父元素作为目标,而不是允许在document级别处理委托。 ie do $("#parent").on("click", element, function() {}) . 即做$("#parent").on("click", element, function() {})

Finally, since <div id="1"> is static, you don't need a delegated event handler, you can bind the handler directly: 最后,由于<div id="1">是静态的,因此不需要委托的事件处理程序,可以直接绑定处理程序:

$("#1").click(function () {
    //...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM