无法访问动态生成的元素 [英] Can't access dynamically generated element

查看:77
本文介绍了无法访问动态生成的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法访问动态生成的元素: 这是我对json请求的功能:

Can't acces dynamically generated element: This is my function for json request:

$.getJSON('/getJSON.php?selectorcat='+var1, function(jsonData){

var LI_list_html = '';
var sum = 0;

if(jsonData[0])
    {
        $.each(jsonData, function(i,value)
        {
        var catname = jsonData[i].name;
        var id = jsonData[i].id;
        var DIV_html = catname;

        LI_list_html = LI_list_html+'<li class="selectorsub" data-catselectsub="'+id+'" id="SelectorSubcat_'+id+'">'+DIV_html+'</li>';
        });
        }
        else
        {
            LI_list_html = 'No subcats there..';
        }

所以当我得到这样的生成的html时:

So when i get the generated html like this:

<ul>
   <li class="selectorsub" data-catselectsub="169" id="SelectorSubcat_169">CAT1</li>
   <li class="selectorsub" data-catselectsub="170" id="SelectorSubcat_170">CAT2</li>
   <li class="selectorsub" data-catselectsub="171" id="SelectorSubcat_171">CAT3</li>
   <li class="selectorsub" data-catselectsub="172" id="SelectorSubcat_172">CAT4</li>
</ul>

我不能接受这种情况:

$("[id^=SelectorSubcat_]").click(function() {
   alert($(this).data('catselectsub'));
});

我认为生成的元素还不是现成的DOM,这就是为什么不能加入它们的原因.

I think the elemen that is generated isn't ready DOM that's why can't acces them.

推荐答案

事件处理程序仅绑定到当前选定的元素;在您的代码进行事件绑定调用时,它们必须存在于页面上.

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

动态创建元素时,需要使用 事件委托 使用 .on() 委托事件方法.

As you are creating elements dynamically, You need to use Event Delegation using .on() delegated-events approach.

$(document).on('event','selector',callback_function)

示例

$(document).on('click', "[id^=SelectorSubcat_]", function(){
    //Your code
});

您应该使用最近的静态容器代替document,以获得更好的性能.

In place of document you should use closest static container For better performance.

这篇关于无法访问动态生成的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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