gpt4 book ai didi

jquery - 向动态创建的按钮 jQuery 添加数据属性

转载 作者:行者123 更新时间:2023-12-01 02:28:29 24 4
gpt4 key购买 nike

我正在 jQuery 中动态创建按钮。我需要添加数据属性:

所以我在这里看到了答案:Dynamically create buttons with Jquery

$(document).ready(function() {
for(i = 1; i <=10; i++) {
$('<button/>', {
text: i, //set text 1 to 10
id: 'btn_'+i,
click: function () { alert('hi'); }
});
}
});

我添加这样的数据属性:

$(document).ready(function() {
for(i = 1; i <=10; i++) {

$('<button/>', {
text: i, //set text 1 to 10
id: 'btn_'+i,
click: function () { alert('hi'); }
}).attr('data-test', 1).attr('data-test2', 2);

}
});

我在想是否可以做一些类似于添加 textid 属性的事情

最佳答案

您可以这样做,但由于 key 包含 - 您需要将 key 作为字符串文字传递,例如

$(document).ready(function() {
for (i = 1; i <= 10; i++) {

$('<button/>', {
text: i, //set text 1 to 10
id: 'btn_' + i,
click: function() {
alert('hi: ' + $(this).attr('data-test'));
},
'data-test': 1
}).appendTo('body');

}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

关于jquery - 向动态创建的按钮 jQuery 添加数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31912728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com