jQuery - 如果SRC包含字符串,则将类应用于图像

时间:2014-06-03 20:06:18

标签: jquery css

我有很多内容,例如

<div id="justThisDIV"><p>Some paragraph <img src="http://mydomain.com/image.jpg"/> </p>
<p><img src="http://mydomain.com/wow.png"/></p>
<p><img src="http://notmydomain.com/blah.png"/> Wow this is boring</p></div>

如何将类添加到我的域中的所有图像,即将ID为dyd的URL包含在ID为justThisDIV

的DIV中

我试过以下但没有去

<script type="text/javascript">
    $(document).ready(function() {
        $("div#justThisDIV img[src*=mydomain.com]").addClass("full-width");

    });
</script>

由于

4 个答案:

答案 0 :(得分:3)

ANSWER再次编辑

您需要添加 'attribute contains' selector ,然后将.parent().attr('id')与条件表达式一起使用,将其添加到您想要添加到的div中。

$("img[src*='imgur']").each(function () {
    if($(this).parent().attr('id')  == "thisDiv") { $(this).addClass('mine')}
});

或者,如果要将类添加到容器中,只需更改引用:

$("img[src*='imgur']").each(function () {
    if($(this).parent().attr('id')  == "thisDiv") { $(this).parent().addClass('mine')}
});

DEMO - 为图片添加课程 DEMO 2 - 在图片容器中添加一个类

答案 1 :(得分:1)

以下正是您所需要的

$('img')
    .filter(function() {
        return this.src.match(/^http:\/\/mydomain.com/);
    })
   .addClass("full-width");

jsfiddle链接:http://jsfiddle.net/4YXDS/

答案 2 :(得分:0)

您可以尝试使用以。开头的属性 示例:

$( "img[src^='mydomain.com']" ).addClass('myClassName');

更多信息:http://api.jquery.com/attribute-starts-with-selector/

答案 3 :(得分:0)

不要在可能不存在的DOM元素上触发函数。检查它们是否存在,然后采取行动。

var $img = $('img[src*="mydomain.com"]');

// Check if at least one image you need exists
if ($img.length) {
    $img.each(function() {
        // Add custom class to each img tag
        $(this).addClass('my_class');
    });
}

确实只能输入以下内容来添加类:

$('img[src*="mydomain.com"]').addClass('my_class');

但是,我觉得这样做很好:

  1. 检查元素是否退出
  2. 保持代码透明
  3. 保持代码易于扩展,以防您将来需要对图像执行不同的操作