JQUERY如何从动态div获取id名称? [英] JQUERY how to get id name from dynamic div?

查看:324
本文介绍了JQUERY如何从动态div获取id名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个动态生成(来自PHP文件)div。这个div是这样的:

 < div id =xclass =myclass>< / div> 
< div id =yclass =myclass>< / div>

其中X和Y是从php文件动态生成的数字。



我试过这种方法:

  $('。myclass')。click(function(){

alert(this.attr(id)) ;

});

但通过这种方式,我只获得第一个id(myclasses的第一个元素)。 >

我该如何解决它?

  $('。myclass')。live('click',function(){
alert(this.id); //或alert($(this).attr('id')));为jQuery方法
});

使用 $。live()函数会将事件绑定到尚不存在的元素,所以当您动态添加新的div.myclass元素时,它们也会被绑定。






请注意:。 .live()现已弃用,请使用 .delegate() .on() 。 code $(document).on('click','.myclass',function(){
alert(this.id);
});


I've got two dynamic generated (from PHP file) divs. This divs are like this:

<div id="x" class="myclass"></div>
<div id="y" class="myclass"></div>

Where X and Y are numbers generated dynamically from a php file. How can I get this id (number) when, for expample, I click on this divs?

I've tried in this way:

$('.myclass').click(function(){

alert(this.attr("id"));

});

But in this way I get only the first id (the first element of myclasses).

How can I fix it?

解决方案

try this instead:

$('.myclass').live('click', function() {
   alert(this.id); //or alert($(this).attr('id'))); for the jQuery method
});

Binding events using the $.live() function will bind events to elements that do not yet exists, so when you add new div.myclass elements dynamically they will be bound as well.


Please Note: .live() is now deprecated, use .delegate() or .on() instead.

$(document).on('click', '.myclass', function() {
    alert(this.id);
});

这篇关于JQUERY如何从动态div获取id名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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