如何通过jQuery获取按钮的data-index?附创建带索引按钮代码
获取Battle索引的正确方法
你的代码存在一个关键问题:点击事件绑定在了.Battle容器div上,但data-index属性是设置在div内部的button标签上的。因此当你调用$(this).data('index')时,实际是在尝试获取div的数据属性,而它并没有这个属性,自然无法拿到正确的索引值。
下面是几种可行的解决方法:
方案1:直接给按钮绑定点击事件
将事件绑定目标改为button元素,这样$(this)就会指向带有data-index的按钮:
let battle_element = `<div class="Battle"> Battle: <button data-index="${battles_list[i].battle_index}">Battle</button></div>`; $('#battles_list').append(battle_element); $(".Battle button").on("click", function() { console.log($(this).data('index')); })
方案2:在容器点击事件中查找内部按钮
如果需要保留整个div的点击区域,可以在div的点击事件里定位到内部的button元素,再获取它的索引:
let battle_element = `<div class="Battle"> Battle: <button data-index="${battles_list[i].battle_index}">Battle</button></div>`; $('#battles_list').append(battle_element); $(".Battle").on("click", function() { console.log($(this).find('button').data('index')); })
方案3:使用事件委托(推荐)
由于你是动态添加DOM元素,使用事件委托能避免重复绑定事件,同时提升性能:
let battle_element = `<div class="Battle"> Battle: <button data-index="${battles_list[i].battle_index}">Battle</button></div>`; $('#battles_list').append(battle_element); // 绑定到父容器,监听内部按钮的点击事件 $('#battles_list').on("click", ".Battle button", function() { console.log($(this).data('index')); })
内容的提问来源于stack exchange,提问作者ezburbon
相关产品推荐
相关产品推荐

