如何替换每个元素上的图像src?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="userShop">
<p class="shoppingbaskets">
<a href="RunFunction.jsp;jsessionid=123456789?shop=querty&basket=empty"><img src="image/empty.png" title="empty" width="50" height="50"></a>
<a href="RunFunction.jsp;jsessionid=123456789?shop=querty&basket=full"><img src="image/full.png" title="full" width="50" height="50"></a>
<a href="RunFunction.jsp;jsessionid=123456789?shop=querty&basket=semi"><img src="image/semi.png" title="semi" width="50" height="50"></a>
<a href="RunFunction.jsp;jsessionid=123456789?shop=querty&basket=abandoned"><img src="image/abandoned.png" title="abandoned" width="50" height="50"></a>
<a href="RunFunction.jsp;jsessionid=123456789?shop=querty&basket=completed"><img src="image/completed.png" title="completed" width="50" height="50"></a>
</p>
</div>
我想根据查询字符串basket
的值替换img src。
例如,如果它是empty
,则其图像src将是newDir/newImageEmpty.jpg
这是我的尝试:
var listStatus = [
{
'name': 'full',
'image': 'http://www.faredelbene.net/img/icon_stumble.png'
},
// and some more for others
];
listStatus.forEach(function (item){
$("#userShop a").each(function(link) {
if (item.name.indexOf(
new URL(this.href).searchParams.get("basket")
) !=-1) {
$(this).find("img").attr({src: item.image});
}
});
})
这是正确的方法吗?
答案 0 :(得分:0)
实际上,有很多方法可以实现
只要在Google上进行一些研究,您就应该能够做到,但是很好。
let links = document.querySelectorAll('a');
console.log("Src before: " + $('#emptyImage').attr('src'));
// Iterate over all links
links.forEach((el) => {
// Get index of 'empty' in string if exists
if (el.search.indexOf('empty') !== -1) {
// Modify src to new src
$(el).find('img').attr("src", "newDir/newImageEmpty.jpg");
}
});
console.log("Src after: " + $('#emptyImage').attr('src'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="userShop">
<p class="shoppingbaskets">
<a href="RunFunction.jsp;jsessionid=123456789?shop=querty&basket=empty"><img id="emptyImage" src="image/empty.png" title="empty" width="50" height="50"></a>
<a href="RunFunction.jsp;jsessionid=123456789?shop=querty&basket=full"><img src="image/full.png" title="full" width="50" height="50"></a>
<a href="RunFunction.jsp;jsessionid=123456789?shop=querty&basket=semi"><img src="image/semi.png" title="semi" width="50" height="50"></a>
<a href="RunFunction.jsp;jsessionid=123456789?shop=querty&basket=abandoned"><img src="image/abandoned.png" title="abandoned" width="50" height="50"></a>
<a href="RunFunction.jsp;jsessionid=123456789?shop=querty&basket=completed"><img src="image/completed.png" title="completed" width="50" height="50"></a>
</p>
</div>