单击时从动态添加的元素获取数据 [英] Get data from dynamically added element on click
问题描述
我有一个可以动态创建元素的函数:
I have a function thats create a element dynamically:
$('#bookUserSeat').on('click', function(){
$('#seatBookings').append('<div class="alert alert-info"><a class="deleteSeat" data-seatNumber="' + $(this).data('seatNumber') + '"><i class="fas fa-trash"></i></div>');
$('#modalBookSeat').modal('hide');
});
现在,我有一个功能可以处理on click事件:
Now I have a function that works on the on click event:
$('#seatBookings').on('click', 'a.deleteSeat', function(){
var seat = $(this).data('seatNumber');
$(this).parent('div').remove();
});
但是var座位是空的.如何从动态创建的链接获取数据属性?
But the var seat is empty. How can I get the data attr from the dynamically created link?
推荐答案
-data
和data()
区分大小写.
但是,当您使用.append()
时,该属性会转换为小写字母,因此您实际上具有不匹配的data-seatnumber
和data("seatNumber")
.
However, the attribute gets converted to lower-case when you use .append()
, so you actually have data-seatnumber
and data("seatNumber")
which don't match.
演示:
$("#mydiv").append('<div data-lowercase="lowercase" data-mixedCase="mixedCase">inner</div>');
console.log("lowerCase", $("#mydiv>div").data("lowerCase"));
console.log("lowercase", $("#mydiv>div").data("lowercase"));
console.log("mixedCase", $("#mydiv>div").data("mixedCase"));
console.log("mixedcase", $("#mydiv>div").data("mixedcase"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv"></div>
如您所见,data-
与mixedCase
添加在一起,但在.data("mixedCase")
上给出了undefined
-但与.data("mixedcase")
都可以使用(均较低).
As you can see, the data-
is added with mixedCase
but gives undefined
on .data("mixedCase")
- but works fine with .data("mixedcase")
(all lower).
始终使用所有较低的属性以实现兼容性.
Always use all-lower attributes for compatibility.
这篇关于单击时从动态添加的元素获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!