【发布时间】:2018-05-15 18:28:57
【问题描述】:
如果我在 HTML 页面中有 5 张图片。我想通过 src 属性值搜索 2 张图像,并向图像标签添加一个新属性。
限制是我不能用任何id或class属性值搜索img标签,我只有src值。在下面的代码中,
我想搜索 2 个具有 src 值的 img 标签,例如 img_src_1 和 img_src_2 并想在 img 标签 nopin= 中添加一个新属性“nopin”。
<html>
<head>
<script>
jQuery(document).ready(function(){
// find img tag by src value and add new attribute nopin="nopin" into this img tag
var img_src_1 = "https://example.com/image-3.jpg";
var img_src_2 = "https://example.com/image-5.jpg";
// find images with src url value is img_src_1 & img_src_2
var result1 = jQuery('img').find('src', img_src_1);
var result2 = jQuery('img').find('src', img_src_2);
// add new attribute nopin="nopin" in both img tag
});
</script>
</head>
<body>
<h1>My Gallery Page</h1>
<p>My Image 1</p>
<img src="https://example.com/image-1.jpg" width="200px" height="200px">
<p>My Image 2</p>
<img src="https://example.com/image-2.jpg" width="200px" height="200px">
<p>My Image 3</p>
<img src="https://example.com/image-3.jpg" width="200px" height="200px">
<p>My Image 4</p>
<img src="https://example.com/image-4.jpg" width="200px" height="200px">
<p>My Image 5</p>
<img src="https://example.com/image-5.jpg" width="200px" height="200px">
</body>
</html>
页面加载后生成的 HTML 应该是这样的
<html>
<body>
<h1>My Gallery Page</h1>
<p>My Image 1</p>
<img src="https://example.com/image-1.jpg" width="200px" height="200px">
<p>My Image 2</p>
<img src="https://example.com/image-2.jpg" width="200px" height="200px">
<p>My Image 3</p>
<img nopin="nopin" src="https://example.com/image-3.jpg" width="200px" height="200px">
<p>My Image 4</p>
<img src="https://example.com/image-4.jpg" width="200px" height="200px">
<p>My Image 5</p>
<img nopin="nopin" src="https://example.com/image-5.jpg" width="200px" height="200px">
</body>
</html>
非常感谢任何帮助,在此先感谢。
【问题讨论】:
-
非常感谢大家的快速回复。我得到了我的问题的确切解决方案,你很快就提供了。
标签: javascript jquery html image