gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:48:54 24 4
gpt4 key购买 nike

我有很多内容,例如

<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 为 justThisDIV 的 DIV 中包含 URL mydomain.com

我试过下面的但是不行

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

});
</script>

谢谢

最佳答案

答案再次编辑

您需要添加 '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 - 添加一个类到图像的容器

关于jQuery - 如果 SRC 包含字符串,则将类应用于图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24024009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com