我正在尝试将一些脚本仅应用于那些图像文件名以文本项开头的img标记。
<img src="site.com/others.png">
<img scr="site.com/item1.png">
<img scr="site.com/item2.png">
<img scr="site.com/item3.png">
所以我只想对这三个图像名称以item开头的图像标记执行一些任务。怎么做?
答案 0 :(得分:2)
此querySelector应该可以工作:
// vanilla
var items = document.querySelectorAll('img[src*="/item"]');
// jquery
$('img[src*="/item"]')
https://www.w3schools.com/cssref/sel_attr_contain.asp
我在选择器中的/
之前添加了item
,以便仅使用item获取开始的内容。
回答有关this
的问题。你的代码在做什么:
this
window
的src
window
(this
)的src。以下是如何更改每个项目的src:
// Find the items
var items = $('img[src*="/item"]');
// Create a function to change their src
function changeSrc(index, item) {
// get the original src
// I've added the replace at the end with a regexp to only get
// the filename and not the whole src path
var filename = $(item)
.attr('src')
.replace(/.*\//, '');
// Change the src
$(item).attr("src","<?php echo $mediaDirectory;?>/"+filename);
}
// If there are items
if (items.length > 0) {
// Run the changeSrc function for each one
$.each(items, changeSrc);
}
答案 1 :(得分:1)
如果您希望图片的图片名称的项目以项目开头,而不是让所有在其中某处有item
的图片源网址,您可以执行以下操作:
[...document.querySelectorAll('img[src]')]
.filter(
img=>
img.src.split("/").slice(-1)[0].indexOf("item")===0
);