如何在不在DOM中的元素上使用jQuery设置数据属性? [英] How to set data attribute with jQuery on element that is not in DOM yet?
本文介绍了如何在不在DOM中的元素上使用jQuery设置数据属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不在DOM中的元素上使用jQuery设置data-attribute?
How can I set the data-attribute with jQuery on an element that is not in the DOM yet?
代码:
var panelHeading = $('<div/>', {class:'panel-heading', href:'#'+username+'PanelContent'});
panelHeading.data('toggle', 'collapse').data('target',"#"+username+"PanelContent");
将数据属性附加到文档时,不会显示数据属性。其他属性确实出现。
The data attributes don't appear when I append it to the document. The other attributes do appear.
推荐答案
您可以在创建元素时添加数据属性
You can add data attributes when creating the element
var panelHeading = $('<div />', {
'class' : 'panel-heading',
href : '#'+username+'PanelContent',
'data-toggle' : 'collapse',
'data-target' : '#'+username+'PanelContent'
});
使用 data()
在内部存储数据在jQuery中,它不会创建HTML属性,因此对于诸如Bootstrap
using data()
stores the data internally in jQuery, it does not create HTML attributes, so it works rather poorly with attributes for things like Bootstrap
这篇关于如何在不在DOM中的元素上使用jQuery设置数据属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文