如何在附加的按钮中获取数据 ID

How can I get the data-id in an appended button?

本文关键字:获取 数据 ID 按钮      更新时间:2023-09-26

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());
    });
});

但是使用此代码,我只能检索文本"此处的一些文本"。但我需要的是附加按钮的数据 ID。

我也尝试了下面的代码,但它不起作用。

JavaScript

$('#submit').click(function(){
    $( "#result" ).each(function( index ) {
        console.log( index + ": " + $( this ).html($(this).html($(this).attr("data-id"))));
    });
});

要获取 #result 元素中按钮的数据 ID,您可以这样做:

$('#submit').click(function(){
    $('#result button').each(function(i){
         console.log(i, ':', $(this).data('id'));
    });
});

试试这个

$('#submit').click(function(){
  console.log($("#result").find("button").data('id'));
});

确保您的ID是唯一的。每个带有 ID 都没有意义

如果用户多次单击#btn"单击此处"按钮,您最终会在#result中附加多个新按钮(这将是无效的 html,因为您将有重复的id值),因此您需要使用 .each() 遍历这些按钮,而不是尝试使用 .each() 遍历#result

$('#submit').click(function(){
    $("#result").find("button").each(function(index ) {
      console.log( index + ": " + $(this).attr("data-id"));
    });
});

演示:http://jsfiddle.net/NXU9e/

注意:#result元素的标记缺少结束</div>标记中的/