简体   繁体   English

DOM的jQuery事件,在document.ready事件之后插入到页面中

[英]jQuery events for DOM which are inserted to the page after document.ready event

I have written a code to select categories, it works for parent categories but does not work for child categories. 我已经编写了用于选择类别的代码,它适用于父类别,但不适用于子类别。

Scenario: The parent cats are a list of DOM elements which are loaded by the page load, but when I click on one of them it makes an ajax request and retrieve the list of its children and then renders them in the page. 场景:父级猫是由页面加载加载的DOM元素列表,但是当我单击其中的一个时,它发出ajax请求并检索其子级列表,然后在页面中呈现它们。 In this way, a new list of DOMs are clicked, now the following javascript code is responsible to attach click event to the generated child cats. 这样,将单击一个新的DOM列表,现在下面的javascript代码负责将click事件附加到生成的子猫上。 However, it does not work, no console error not anything else, as if there is no JS at all. 但是,它不起作用,没有控制台错误,没有别的什么,好像根本没有JS。

//***** SELECTING CHILD CATEGORIES *****/
            var child_cat = $('.new-child-item');
            child_cat.click(function(){alert("AAA");});
            child_cat.on('click', function(){
                console.log("Very Fine");
                if($(this).hasClass('active-child'))
                {
                    $(this).addClass('new-child-item');
                    $(this).addClass('inactive-child');
                    $(this).removeClass('active-child');    
                }
                else
                {
                    $(this).addClass('new-child-item-active');
                    $(this).addClass('active-child');
                    $(this).removeClass('inactive-child');                      
                }
            });         
            //**** SELECTING CHILD CATEGORIES ***/

And here is the generated child cats when the user clicks on its parent: 这是用户单击其父级时生成的子级猫:

<div style="display: block;" class="new-item-cats-list-holder clearfix"><div class="inactive-child new-child-item" id="5">
                نرم افزار       
                </div><label class="new-item-side-label"></label><div class="inactive-child new-child-item" id="6">
                سخت افزار       
                </div><label class="new-item-side-label"></label><div class="inactive-child new-child-item" id="7">
                ICDL       
                </div><label class="new-item-side-label"></label><div class="inactive-child new-child-item" id="8">
                شبکه       
                </div><label class="new-item-side-label"></label><div class="inactive-child new-child-item" id="9">
                برنامه نویسی       
                </div><label class="new-item-side-label"></label><div class="inactive-child new-child-item" id="10">
                طراحی       
                </div><label class="new-item-side-label"></label><div class="inactive-child new-child-item" id="11">
                اینترنت       
                </div><label class="new-item-side-label"></label><div class="inactive-child new-child-item" id="12">
                طراحی سایت       
                </div><label class="new-item-side-label"></label><div class="inactive-child new-child-item" id="13">
                تایپ       
                </div><label class="new-item-side-label"></label></div>

You need event delegation for dynamically added elements. 您需要事件委托才能动态添加元素。 Use other version of on() for event delegation. 使用其他版本的on()进行事件委派。

$(document).on('click', '.new-child-item', function(){
    console.log("Very Fine");
    if($(this).hasClass('active-child'))
    {
        $(this).addClass('new-child-item');
        $(this).addClass('inactive-child');
        $(this).removeClass('active-child');    
    }
    else
    {
        $(this).addClass('new-child-item-active');
        $(this).addClass('active-child');
        $(this).removeClass('inactive-child');                      
    }
});         

You have to delegate event to static parent of dynamically added element which is present at the time the event binding code is executed or you can delegate to document/body . 您必须将事件委托给动态添加的元素的static父对象,该元素在执行事件绑定代码时存在,或者可以委托给document/body

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. 委派事件的优势在于,它们可以处理来自后代元素的事件,这些事件在以后的时间添加到文档中。 By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery doc 通过选择在附加委托事件处理程序时保证存在的元素,您可以使用委托事件来避免频繁附加和删除事件处理程序的需要, jQuery文档

The 'click' method sets events for objects that are created when the page loads. “ click”方法设置页面加载时创建的对象的事件。 To add events to objects that have not been created yet you should use the 'delegate' method ( http://api.jquery.com/delegate/ ) 要将事件添加到尚未创建的对象,应使用'delegate'方法( http://api.jquery.com/delegate/

Basic example here: http://jsfiddle.net/ka_tee_jean/N9EJS/ 此处的基本示例: http : //jsfiddle.net/ka_tee_jean/N9EJS/

// initial event on category
$('.cat').on('click',function() {
    $(this).after("<br><span class='new-child-item'>I'm a sub cat</span>");
});

// This won't work cause there are no new-child-items yet
$('.new-child-item').on('click',function() {
    alert("I will never fire");
});

// tell jQuery that this event needs to fire on 
// existing and also on new instances of class new-child-item
// when they are created
$('body').delegate('.new-child-item','click',function() {
    alert("I will fire");
});

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

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