简体   繁体   English

如何访问动态创建的锚标签jQuery的数据属性

[英]How to access data attribute of dynamically created anchor tag jquery

When trying to retrieve the "data" attributes of a dynamically created anchor element, the function is unable to navigate $this to the attributes. 尝试检索动态创建的锚元素的“数据”属性时,该函数无法将$ this导航到属性。

I've tried to use 'attr()' and navigate using 'closest()' but I'm unable to progress into the attributes: NamedNodeMap. 我尝试使用'attr()'并使用'closest()'进行导航,但无法进入以下属性:NamedNodeMap。

 function populateDropdown(data) { data = JSON.parse(data); let anchorItem = $(' <a class="dropdown-item disabled" href="#" id = "imagingSelection" > Imaging < /a>'); let anchorDivider = $('<div class="dropdown-divider"></div>'); $("#typeSelection").append(anchorItem); $("#typeSelection").append(anchorDivider); for (var i = data.length - 1; i >= 0; i--) { let anchorItem = $(`<a id="anchor${i}" class="dropdown-item" href="#" data-sensitivity:"${data[i].sensitivity}" data-specicifity:"${data[i].specicifity}" data-nnh:"${data[i].numberToHarm}">${data[i].name}</a>`) $("#typeSelection").append(anchorItem); } } //Deal with click on dynamic DOM anchor creation $('body').on('click', 'a.dropdown-item', function() { console.log($(this)); }); 

The console shows k.fn.init [a#anchor1.dropdown-item], which when I expand I can see the attributes in NamedNodeMap that I want, but cannot find a way to access 控制台显示k.fn.init [a#anchor1.dropdown-item],当我展开时,可以在NamedNodeMap中看到所需的属性,但是找不到访问方法

You need to use = after the data-XXX attributes, not : , eg data-sensitivity="${data[i].sensitivity}" . 您需要在data-XXX属性后使用= ,而不是: ,例如data-sensitivity="${data[i].sensitivity}"

Or you could use jQuery's method for creating elements. 或者,您可以使用jQuery的方法来创建元素。

Then use .data() to access the data attribute. 然后使用.data()访问data属性。 jQuery won't actually put it in a DOM attribute; jQuery实际上不会将其放在DOM属性中。 see get wrong value in data attribute jquery 看到数据属性jQuery中得到错误的值

BTW, you misspelled "specificity". 顺便说一句,您拼写了“特殊性”。

 function populateDropdown(data) { data = JSON.parse(data); let anchorItem = $(' <a class="dropdown-item disabled" href="#" id = "imagingSelection" > Imaging < /a>'); let anchorDivider = $('<div class="dropdown-divider"></div>'); $("#typeSelection").append(anchorItem); $("#typeSelection").append(anchorDivider); for (var i = data.length - 1; i >= 0; i--) { let anchroItem = $("<a>", { id: `anchor${i}`, "class": "dropdown-item", href: "#", data: { sensitivity: data[i].sensitivity, specicifity: data[i].specicifity, nnh: data[i].numberToHarm }, text: data[i].name }); $("#typeSelection").append(anchorItem); } } //Deal with click on dynamic DOM anchor creation $('body').on('click', 'a.dropdown-item', function() { console.log($(this).data("sensitivity")); }); 

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

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