Joo*_*nas 14 jquery html5 custom-data-attribute
所以jquery api说如下:
从jQuery的内部.data()缓存中删除数据不会影响文档中的任何HTML5数据属性; 使用.removeAttr()来删除它们.
删除单个数据属性没有问题.
<a title="title" data-loremIpsum="Ipsum" data-loremDolor="Dolor"></a>
$('a').removeAttr('data-loremipsum');
Run Code Online (Sandbox Code Playgroud)
问题是,如何删除多个数据属性?
更多细节:
起点是我有多个(比如说... 60)不同的数据属性,我想删除所有这些属性.
首选方法是仅定位包含该单词的那些数据属性lorem.在这种情况下lorem,始终是第一个字.(如果你算的话,还是第二个data-)
另外,我想保持所有其他属性不变
And*_*son 13
// Fetch an array of all the data
var data = $("a").data(),
i;
// Fetch all the key-names
var keys = $.map(data , function(value, key) { return key; });
// Loop through the keys, remove the attribute if the key contains "lorem".
for(i = 0; i < keys.length; i++) {
if (keys[i].indexOf('lorem') != -1) {
$("a").removeAttr("data-" + keys[i]);
}
}
Run Code Online (Sandbox Code Playgroud)
在这里小提琴:http://jsfiddle.net/Gpqh5/
在我的jQuery占位符插件中,我使用以下内容来获取给定元素的所有属性:
function args(elem) {
// Return an object of element attributes
var newAttrs = {},
rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
Run Code Online (Sandbox Code Playgroud)
请注意,这elem是一个元素对象,而不是jQuery对象.
你可以轻松地调整它,只获取data-*属性名称:
function getDataAttributeNames(elem) {
var names = [],
rDataAttr = /^data-/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && rDataAttr.test(attr.name)) {
names.push(attr.name);
}
});
return names;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以遍历生成的数组,并调用removeAttr()元素上的每个项目.
这是一个简单的jQuery插件,可以做到这一点:
$.fn.removeAttrs = function(regex) {
return this.each(function() {
var $this = $(this),
names = [];
$.each(this.attributes, function(i, attr) {
if (attr.specified && regex.test(attr.name)) {
$this.removeAttr(attr.name);
}
});
});
};
// remove all data-* attributes
$('#my-element').removeAttrs(/^data-/);
// remove all data-lorem* attributes
$('#my-element').removeAttrs(/^data-lorem/);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13056 次 |
| 最近记录: |