我对jQuery不是很熟悉,我必须完成以下任务。 我想在不使用jQuery的情况下从网页中的所有图像中删除类。 我能用JQuery找到这个修复但我需要用JavaScript修复它。如果有人能够指导我这件事,我将不胜感激。 谢谢!
答案 0 :(得分:3)
一种简单的现代方式:
[].forEach.call(document.images, x=>x.removeAttribute("class"));
另一种更新颖的方式:
for(let img of document.images) img.className="";
更安全的方式:
for(var i in document.images) if(i-.1)document.images[i].className = "";
另一种较旧的方式,比第一种更好(感谢@mplungjan):
for(var d=document.images, i=d.length-1;i;i--) d[i].removeAttribute("class");
答案 1 :(得分:3)
尝试使用此功能
/**
* Removes all class attributes from all the images, if a class has been passed then it only removes that className
* @param {string} [className=] optional parameter, only images with that className will be affected and will only lose that className
* @returns {void}
*/
function removeImageClasses(className) {
var validClass = typeof className === "string";
var selector = validClass? "." + className : "";
var list = document.querySelectorAll("img" + selector);
for(var index = 0; index < list.length; index++) {
if(validClass) list[index].classList.remove(className);
else list[index].removeAttribute("class");
}
}
这是一个有效的演示
(function() {
var original = '<img class="blue"><img class="blue"><img class="green"><img class=""><img class/>';
var images = document.getElementById("image-list");
function removeImageClasses(className) {
var validClass = typeof className == "string";
var selector = validClass ? "." + className : "";
var list = document.querySelectorAll("img" + selector);
for (var index = 0; index < list.length; index++) {
if (validClass) list[index].classList.remove(className);
else list[index].removeAttribute("class");
}
}
function reset() {
images.innerHTML = original;
}
function onClick(id, callBack) {
document.getElementById(id).addEventListener("click", callBack);
}
onClick("remove-blue", function() {removeImageClasses("blue")});
onClick("remove-green", function() {removeImageClasses("green")});
onClick("remove-yellow", function() {removeImageClasses("yellow")});
onClick("remove-all", removeImageClasses);
onClick("reset", reset);
})();
#image-list {
margin-top: 10px;
}
img {
background-color: transparent;
display: block;
float: left;
height: 50px;
width: 50px;
}
img.blue {
background-color: blue;
}
img.green {
background-color: green;
}
<button id="remove-blue">Remove Blue</button>
<button id="remove-green">Remove Green</button>
<button id="remove-yellow">Remove Yellow</button>
<button id="remove-all">Remove All</button>
<button id="reset">Reset</button>
<div id="image-list">
<img class="blue" />
<img class="blue" />
<img class="green" />
<img class="" />
<img class/>
</div>
答案 2 :(得分:0)
这应该完成任务。
for(var i = 0, len = document.images.length; i < len; i++)
document.images[i].className = "";
})