javascript - 如何获取附加按钮中的数据 ID?

标签 javascript jquery html

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/

相关文章:

javascript - TypeScript - 元素上的函数

javascript - 提高 FullCalendar 渲染性能

javascript - 在 fancybox 中加载各种尺寸的图像

c# - 如何根据另一个选择下拉jquery MVC过滤一个选择?

html - 样式禁用 <select multiple> 控件

asp.net - 如何 : Background image should remain static but the webpage on it must scroll down in asp. 网络

对象上的 Javascript 字符串等效项

javascript - 在模板文本中插入 jQuery 元素的有效方法

jquery - 在涉及许多 subview 的复杂表单中,您使用什么模式进行表单验证

javascript - 一个单一文件的 WebAssembly html 演示