简体   繁体   English

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

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

JavaScript 的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 的HTML

<button id="btn">CLICK HERE</button>
<div id='result'></div>
<button id="submit">SUBMIT HERE</button>

I want to display the data-id='show' from the appended button after i click the button with an id="submit" . 我想在单击带有id="submit"按钮后data-id='show'附加按钮的data-id='show' As you can see, the div with id="result" is just like an container of all the appended text. 如您所见,具有id="result"的div就像所有附加文本的容器一样。

So far, this is what I have, 到目前为止,这就是我所拥有的,

JavaScript 的JavaScript

$('#submit').click(function(){
    $( "#result" ).each(function( index ) {
        console.log( index + ": " +$(this).text());
    });
});

But with this code, i can only retrieve the text, "some text here". 但是使用此代码,我只能检索文本“此处有一些文本”。 But what i needed is the data-id of my appended button. 但是我需要的是附加按钮的data-id。

I also tried the code below, but it is not working. 我也尝试了下面的代码,但无法正常工作。

JavaScript 的JavaScript

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

To get the data-id of the buttons you have in the #result element, you may do this : 要获取#result元素中按钮的数据ID,可以执行以下操作:

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

try this 尝试这个

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

make sure you id is unique.... each with ids does not make sense 确保您的ID是唯一的...。每个ID都没有意义

If the user clicks the #btn "CLICK HERE" button more than once you will end up with multiple new buttons appended within #result (which would be invalid html given that you'd then have duplicate id values), so you'd need to loop through those buttons with .each() rather than trying to loop through #result with .each() : 如果用户#btn单击#btn “点击此处”按钮,您将最终在#result附加多个新按钮(由于您将有重复的id值,因此这将是无效的html),因此您需要使用.each()遍历这些按钮,而不是尝试使用.each()遍历#result

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

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

NOTE: The markup for your #result element is missing the / in the closing </div> tag. 注意: #result元素的标记在结束</div>标记中缺少/

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

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