将数据属性添加到DOM [英] Adding data attribute to DOM

查看:121
本文介绍了将数据属性添加到DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$('div').data('info', 1);

alert($('div').data('info'));
//this works    

$('div[data-info="1"]').text('222');
//but this don't work

我在jquery中创建元素。之后,我想添加属性数据。他喜欢并且被添加了,但是在DOM中,这并不明显,我无法获得该项目,使用

I'm creating element within jquery. After that, I want to add attribute "data". He's like and is added, but in the DOM, this is not apparent, and I can't get the item, using

$('div[data-example="example"]').html()

jsfiddle

推荐答案

使用 .data()方法:

$('div').data('info', '222');

请注意,这不会创建实际的 data-info 属性。如果您需要创建属性,请使用 .attr()

Note that this doesn't create an actual data-info attribute. If you need to create the attribute, use .attr():

$('div').attr('data-info', '222');

这篇关于将数据属性添加到DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆