简体   繁体   English

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

[英]How to set data attribute with jQuery on element that is not in DOM yet?

How can I set the data-attribute with jQuery on an element that is not in the DOM yet? 如何在尚未在DOM中的元素上使用jQuery设置数据属性?

Code: 码:

   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. 其他属性确实出现。

jQuery's data() method doesn't set HTML5 data- attributes, it actually stores high-level data in the DOM element. jQuery的data()方法未设置HTML5 data-属性,而是将高级数据实际上存储在DOM元素中。 You can store complex objects and functions using data() that you can't using attributes. 您可以使用不能使用属性的data()存储复杂的对象和函数。

If you really must set an attribute, use attr('data-toggle','collapse') and the like. 如果确实必须设置属性,请使用attr('data-toggle','collapse')等。 But as mentioned in an earlier comment, why not just set it in the initial declaration? 但是,正如前面的评论中提到的,为什么不只是在初始声明中设置它呢?

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'
});

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 使用data()将数据内部存储在jQuery中,它不会创建HTML属性,因此它与Bootstrap之类的属性配合使用时效果很差

You can use: 您可以使用:

var panelHeading = $('<div data-target="' + '#'
    + username + 'PanelContent' + '"/>');

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

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