我试图将一些脚本仅应用于那些图像文件名以文本项开头的 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 开头的图像标签执行一些任务。怎么办?
最佳答案
这个查询选择器应该可以工作:
// vanilla
var items = document.querySelectorAll('img[src*="/item"]');
// jquery
$('img[src*="/item"]')
https://www.w3schools.com/cssref/sel_attr_contain.asp
编辑
我在选择器中的 item
之前添加了 /
,以仅获取以 item开头的项目。
编辑2
回答您关于此
的问题。您的代码正在执行的操作是:
- 检查是否存在任何项目
- 尝试查找
this
的 src,即window
- 然后尝试更改
窗口
的src(this
)。
以下是更改每个项目的 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);
}
关于javascript - 如果图像源文件名中的图像以特定文本开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48555542/