在jquery中读取动态创建的元素数据属性? [英] Read dynamically created elements data attribute in jquery?
问题描述
这是我的代码 http://jsfiddle.net/amolw/6kdHG/
按钮是动态创建的(通常按钮的数据将通过AJAX请求)。为简单起见,我对这些值进行了硬编码。
我的问题是当我执行这个 thisHotel = $(this).data('hname');
我未定义变量 thisHotel
。
如果我用锚标签替换按钮会发生同样的事情。
This is my code http://jsfiddle.net/amolw/6kdHG/
The buttons are created dynamically (usually the data for buttons will come through AJAX request). For simplicity I've hard coded those values.
My problem is when i execute this thisHotel = $(this).data('hname');
I get undefined in the variable thisHotel
.
Same thing happens if i replace the buttons with anchor tag.
推荐答案
this $你的例子中的c $ c>是
div id = hotels
。如果您已经进入了div并选择了按钮,那将会奏效。我提出了另一种解决方案。
this
in your example is the div id=hotels
. It would have worked if you would have gone INTO the div and selected the button. I propose another solution though.
http://jsfiddle.net/6kdHG/ 3 /
您可以使用活动目标获取所需信息。
You can use the target of the event to get the information you want.
$("[id^='hotel']").on('click', function (e) {
thisHotel = $(e.target).data('hname');
$("#selected").html("Selected Hotel " + thisHotel);
});
e
是被触发的事件你只需访问它的目标。
e
is the event that got triggered and you simply access it's target.
这篇关于在jquery中读取动态创建的元素数据属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!