jq获取id的名称_JQUERY如何从动态div获取id名称?

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:

$('.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);

});

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页