簡體   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