繁体   English   中英

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

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

的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'附加按钮的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元素中按钮的数据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单击#btn “点击此处”按钮,您将最终在#result附加多个新按钮(由于您将有重复的id值,因此这将是无效的html),因此您需要使用.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>标记中缺少/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM