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

风格不统一 提交于 2019-12-02 22:59:36

问题


How can I set the data-attribute with jQuery on an element that is not in the DOM yet?

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.


回答1:


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




回答2:


jQuery's data() method doesn't set HTML5 data- attributes, it actually stores high-level data in the DOM element. You can store complex objects and functions using data() that you can't using attributes.

If you really must set an attribute, use attr('data-toggle','collapse') and the like. But as mentioned in an earlier comment, why not just set it in the initial declaration?




回答3:


You can use:

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


来源:https://stackoverflow.com/questions/22463182/how-to-set-data-attribute-with-jquery-on-element-that-is-not-in-dom-yet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!