【问题标题】:Filter a word in a image src with jquery使用 jquery 过滤图像 src 中的单词
【发布时间】:2012-09-09 05:28:42
【问题描述】:

我正在尝试过滤我的图像 src 中的特定单词(“无图像”),如果它返回 true,我想删除该特定图像但保留其余图像。

这是我的输出:

<div class="product">
  <div class="image">
   <img src="mytee-red.jpg">
   <img src="mytee-blue.jpg">
   <img src="mytee-black.jpg">
   <img src="mytee-no-image.jpg">
 </div>
</div>

这是我迄今为止尝试过的,但似乎无法正常工作:

var keyword = "no-image";
 $(".product .image img").filter(function(index) {
    if ($(this).attr("src") == keyword) {
        $(this).remove();
    }
});

任何帮助都会很棒!!!

【问题讨论】:

  • == 检查一个字符串是否等于另一个字符串

标签: jquery regex string filter


【解决方案1】:

您可以将其简化为单个命令 -

$(".product .image img[src*='no-image']").remove();

jQuery attribute contains selector 将帮助您在src 属性中的任何位置精确定位您想要包含文本“no-image”的元素。

这是匹配的最慷慨的 jQuery 属性选择器 反对一个价值。如果选择器的字符串,它将选择一个元素 出现在元素属性值中的任何位置。

【讨论】:

    【解决方案2】:

    其他答案提出了更好的方法,但filter() 的演示可能是:

    var keyword = "no-image";
     $(".product .image img").filter(function(index) {
        return $(this).attr("src").match(keyword);
    }).remove();
    

    【讨论】:

      【解决方案3】:

      根据您的示例,您需要使用match() 而不是==

      var keyword = "no-image";
       $(".product .image img").filter(function(index) {
          if ($(this).attr("src").match(keyword)) {
              $(this).remove();
          }
      });
      

      假设您要删除 &lt;img src="mytee-no-image.jpg"&gt;,因为它与关键字 no-image 匹配

      【讨论】:

        【解决方案4】:
        $('.product .image img[src*="no-image"]').remove();
        

        http://api.jquery.com/attribute-contains-selector/

        不需要正则表达式。

        【讨论】:

          【解决方案5】:

          过滤器只会保留传递函数返回 true 的项目。与其尝试在过滤器函数中删除它们,不如返回 false。

          .filter( function(index) ):将匹配元素的集合减少为匹配选择器或通过函数测试的元素。

          var keyword = "no-image";
           $(".product .image img").filter(function(index) {
              return $(this).attr("src") != keyword;
          });
          

          【讨论】:

          • 仅过滤它们不足以将其删除(提供的关键字也不完全匹配,因此应在内容中搜索)。
          猜你喜欢
          • 1970-01-01
          • 2012-02-27
          • 1970-01-01
          • 1970-01-01
          • 2012-08-07
          • 2011-10-20
          • 1970-01-01
          • 1970-01-01
          • 2012-08-28
          相关资源
          最近更新 更多