javascript – 为什么jQuery不会删除所有数据属性?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 为什么jQuery不会删除所有数据属性?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2163字,纯文字阅读大概需要4分钟。
内容图文
![javascript – 为什么jQuery不会删除所有数据属性?](/upload/InfoBanner/zyjiaocheng/749/8b5bbf278e5b46bd8ac4b3b98df1db2e.jpg)
正如标题所说:为什么jQuery不会删除所有数据属性?
<div data-subject-name="Spanisch" data-subject-id="9" data-subject-alias="Spa" data-category-id="1"></div>
$.fn.removeAttrs = function(regex) {
var regex = new RegExp(regex, "g");
return this.each(function() {
var _this = $(this);
console.log(this.attributes);
$.each(this.attributes, function(i, attrib){
console.log(attrib);
if (attrib && attrib.specified && regex.test(attrib.name)) {
console.log(attrib.name);
_this.removeAttr(attrib.name);
}
});
});
};
$('div').removeAttrs('^(data-)');
这是http://jsfiddle.net/g2pXt/8/
我正在使用Remove multiple html5 data-attributes with jquery @Mathias Bynens的剪辑,但它无法正常工作.那么这个解决方案的问题是什么?
解决方法:
实际上,您的代码存在两个问题,每个问题都会部分掩盖另一个问题.
“test called multiple times on the same global regular expression instance will advance past the previous match.”因此,每次使用相同的正则表达式执行.test时,都不会从字符串的开头搜索.我用str.search(regex)> = 0替换了regex.test(str)来解决这个问题.
此外,您的脚本似乎有索引问题,因为您正在循环中删除属性.我相信这是因为“Arrays and array-like objects with a length property…are iterated by numeric index, from 0 to length-1.”在循环解决问题后立即删除所有属性(.removeAttr()将接受要删除的以空格分隔的属性列表.)
$.fn.removeAttrs = function(regex) {
var regex = new RegExp(regex, "g");
return this.each(function() {
var _this = $(this);
var removethese = '';
$.each(this.attributes, function(i, attrib){
if (attrib && attrib.specified && attrib.name.search(regex)>=0) {
removethese += ' '+attrib.name;
}
});
_this.removeAttr(removethese);
});
};
http://jsfiddle.net/mblase75/YHyjC/
请注意,以这种方式使用.removeAttr()实际上是第二次重复循环,因此为了获得最大效率,您应该重新调整代码并使用for循环,该循环通过this.attributes向后计数并同时删除它们.但是,对于一组短的属性,性能增益将是最小的.
$.fn.removeAttrs = function(regex) {
var regex = new RegExp(regex, "g");
return this.each(function() {
var _this = $(this);
for (var i=this.attributes.length-1; i>=0; i--){
var attrib = this.attributes[i];
if (attrib && attrib.specified && attrib.name.search(regex)>=0) {
_this.removeAttr(attrib.name);
}
}; // end for
});
};
http://jsfiddle.net/mblase75/Zm4qR/
内容总结
以上是互联网集市为您收集整理的javascript – 为什么jQuery不会删除所有数据属性?全部内容,希望文章能够帮你解决javascript – 为什么jQuery不会删除所有数据属性?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。