JavaScript
$("#btn").on('click', function(){
$("#result").append("<button type='button' id='btnid'
data-id='show' //this is what I want to get
class='close pull-right' aria-hidden='true'>some text here</button>");
});
HTML
<button id="btn">CLICK HERE</button>
<div id='result'></div>
<button id="submit">SUBMIT HERE</button>
我想在单击带有 id="submit"
的按钮后显示附加按钮中的 data-id='show'
。正如您所看到的,带有 id="result"
的 div 就像所有附加文本的容器。
到目前为止,这就是我所拥有的,
JavaScript
$('#submit').click(function(){
$( "#result" ).each(function( index ) {
console.log( index + ": " +$(this).text());
});
});
但是使用这段代码,我只能检索文本“这里有一些文本”。但我需要的是附加按钮的 data-id。
我也尝试了下面的代码,但它不起作用。
JavaScript
$('#submit').click(function(){
$( "#result" ).each(function( index ) {
console.log( index + ": " + $( this ).html($(this).html($(this).attr("data-id"))));
});
});
最佳答案
要获取 #result
元素中按钮的 data-id,您可以执行以下操作:
$('#submit').click(function(){
$('#result button').each(function(i){
console.log(i, ':', $(this).data('id'));
});
});
关于javascript - 如何获取附加按钮中的数据 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19443158/