我正在尝试编写一个删除所有数据属性(“data-pauze”属性除外)的函数。我今天下午写的那个还可以,但不会删除所有内容。我需要运行它三遍才能删除所有内容。
function removeAllDataAttributes() {
$('section').each(function(a, b) {
var section = $(this);
$.each(this.attributes, function(a, b) {
if (b !== undefined) {
var attr = b.name;
if (attr != 'data-pauze' && !attr.indexOf('data-')) {
console.log(attr);
section.removeAttr(attr);
}
}
});
});
}
$('button').click(function() {
removeAllDataAttributes();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<button>Remove data stuff</button>
<section id="one" data-0="top: 0px;" data-737="top: -737px;" class="skrollable skrollable-between" style="top: 0px;">
<h1>One</h1>
</section>
<section id="two" data-0="top: 737px;" data-737="top: 0px;" data-1397="top: -660px;" class="skrollable skrollable-between" style="top: 737px;">
<h1>Two</h1>
</section>
<section id="three" data-pauze="slider" data-0="top: 1397px;" data-1397="top: 0px;" data-7397="top: 0px;" data-7857="top: -460px;" class="skrollable skrollable-between" style="top: 1397px;">
<h1>Three</h1>
</section>
<section id="four" data-1397="top: 460px;" data-7397="top: 460px;" data-0="top: 1857px;" data-7857="top: 0px;" data-8594="top: -737px;" class="skrollable skrollable-between" style="top: 1857px;">
<h1>Four</h1>
</section>
<section id="five" data-0="top: 8594px;" data-8594="top: 0px;" data-9331="top: -737px;" class="skrollable skrollable-between" style="top: 8594px;">
<h1>Five</h1>
</section>
<section id="six" data-pauze="slider" data-0="top: 9331px;" data-9331="top: 0px;" data-15331="top: 0px;" data-16068="top: -737px;" class="skrollable skrollable-between" style="top: 9331px;">
<h1>Six</h1>
</section>
<section id="seven" data-9331="top: 737px;" data-15331="top: 737px;" data-0="top: 10068px;" data-16068="top: 0px;" data-16805="top: -737px;" class="skrollable skrollable-between" style="top: 10068px;">
<h1>Seven</h1>
</section>
<section id="eight" data-0="top: 16805px;" data-16805="top: 0px;" class="skrollable skrollable-between" style="top: 16805px;">
<h1>Eight</h1>
</section>
我还制作了Codepen:http://codepen.io/frankbiemans/pen/VPRdjw 。
你们知道我做错了什么吗? 谢谢您的帮助。
最佳答案
我认为问题在于使用indexOf,因为如果未找到项目,它会返回-1
,因此替换!attr.indexOf('data-')
到 attr.indexOf('data-') == -1
或 !~attr.indexOf('data-')
,其中 ~
是按位非 (~-1 == 0
)。
关于javascript - 删除所有数据属性的功能,需要多次运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42254986/