如何在不在DOM中的元素上使用jQuery设置数据属性?

如何在不在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