如果图像源文件名中的图像以特定文本开头

时间:2018-02-01 04:49:54

标签: javascript jquery

我正在尝试将一些脚本仅应用于那些图像文件名以文本项开头的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开头的图像标记执行一些任务。怎么做?

2 个答案:

答案 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获取开始的内容。

编辑2

回答有关this的问题。你的代码在做什么:

  1. 检查是否存在任何项目
  2. 试图找到this
  3. window的src
  4. 然后尝试更改windowthis)的src。
  5. 以下是如何更改每个项目的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
);