jQuery cannot obtain the dynamically added dom element node

Encounter problems:

When I obtained $(".the userNames ")page element and made it show and hide, I found that the element could not be hidden, and I could not get it no matter what.

All elements in #top here are dynamically rendered;

Cause of the problem:

Because the page has already loaded the JS, if a new request is made at this time to dynamically add the node, it will naturally not be obtained.

solution:

After consulting the information on the Internet, I found that dynamically added tags require event delegation to obtain the node, which means that you need to use:

$(selector).on(events,[selector],[data],fn)

Note:
1. .userNames is the parent node of the dynamically added node. Please use a non-dynamically added parent node, otherwise it will not be obtained. Dynamically add click nodes in
:<div id = "top"></div>

 $('#top').on('mouseenter', '.hii',function() {
        $(".userNames").show()
    })
    $('#top').on('mouseleave ', '.userNames',function () {
        $('.userNames').hide()
    })

2. Please entrust the non-dynamic addition of nodes to your direct superiors and do not expand the scope.

Please do not write as:

$(div).on('click', '.c', function () {
alert(123);
});

or

$('.c').on('click', function () {
alert(123);
});

Guess you like

Origin blog.csdn.net/weixin_52691965/article/details/125184934