如何获取由jquery创建的数据属性内容? (参见下文)
html
<div data-number="1">
<a href="#" class="element_with_a_data_attribute">element with a data attribute</a>
</div>
<div class="show_and_hide_element" data-idty="show">
<a href="#" class="data_attribute_displayer">Click me to show the data attribute that exist in this parent element</a>
</div>
脚本
//hide the show_and_hide_element
$('.show_and_hide_element').hide();
//if click the .element_with_a_data_attribute
$('.element_with_a_data_attribute').click(function(){
//put its parent data attribute (data-number) into a variable named "datanumber"
var datanumber = $(this).parent("div").attr("data-number");
//then add the datanumber as a data attribute (data-number) to the div that has a class of "show_and_hide_element"
$('.show_and_hide_element').attr("data-number", datanumber);
//show the .show_and_hide_element div
$(".show_and_hide_element").show();
});
//if click the data_attribute_displayer
$('.data_attribute_displayer').click(function(){
//if the parent (div .show_and_hide_element) attribute named "data-idty" of this element is equal to show.
if($(this).parent("div").attr("data-idty") === "show"){
//popup (alert thing) the data number of its parent element (the div)
alert($(this).parent().attr("data-number"));
}
});
从上面的代码引用中可以看出,如果有一个element_with_a_data_attribute类的链接是click,那么它将从其父级(包装此链接的div)获取属性名称data-number,然后添加其父级属性为具有show_and_hide_element类的div然后接下来,如果具有data_attribute_displayer类的链接是单击,则它获取其父属性名为&#34; data-number&#34;当触发了具有element_with_a_data_attribute类的链接但遗憾的是,无法正常工作时添加的内容。任何帮助,想法,线索,建议,建议将不胜感激。谢谢。