JQUERY如何从动态div获取id名称? [英] JQUERY how to get id name from dynamic div?
问题描述
我有两个动态生成(来自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元素时,它们也会被绑定。
请注意:。 I've got two dynamic generated (from PHP file) divs. This divs are like this: 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: But in this way I get only the first id (the first element of myclasses). How can I fix it? try this instead: Binding events using the Please Note:
这篇关于JQUERY如何从动态div获取id名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! .live()
现已弃用,请使用 .delegate()
或 .on()
。 code $(document).on('click','.myclass',function(){
alert(this.id);
});
<div id="x" class="myclass"></div>
<div id="y" class="myclass"></div>
$('.myclass').click(function(){
alert(this.attr("id"));
});
$('.myclass').live('click', function() {
alert(this.id); //or alert($(this).attr('id'))); for the jQuery method
});
$.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.
.live()
is now deprecated, use .delegate()
or .on()
instead.$(document).on('click', '.myclass', function() {
alert(this.id);
});