我正在尝试删除jQuery依赖项,并用循环替换此.each证明很棘手。
// inline <img> when src = .svg so it is styled with CSS
$('[src$=".svg"]').each(function() { // get .svg
var $img = $(this);
var imgURL = $img.attr("src"); // get src url
$.get(
imgURL,
function(data) { // Get the SVG guts from image file
var $svg = $(data).find("svg");
$img.replaceWith($svg); // Replace img with SVG guts
}, "xml"
);
});
答案 0 :(得分:1)
浏览器实现jQuery样式的选择器和集合方法。因此,可以使用document.querySelectorAll
在香草JavaScript中模拟jQuery的每个循环,以返回NodeList
,这是一个类似于数组的对象,有点像jQuery集合:
const nodeList = document.querySelectorAll('[src$=".svg"]')
您可以从数组中借用forEach
方法:
Array.prototype.forEach.call(nodeList, node => {
// do something
})
大多数浏览器(IE浏览器除外)实际上直接在forEach
上支持NodeList
方法:
nodeList.forEach(node => {
// do something
})
您还可以使用for / while循环并使用方括号语法访问各个元素:
for (let i = 0; i < nodeList.length; i++) {
// current element is nodeList[i]
}