在过去的几个小时里,我一直在寻找一种方法来做到这一点,但一无所获。我正在尝试找出一种仅更改属性中的子字符串的方法。我想做的一个例子是改变
<a href="media/gallery/jtnp/JT.JPG" rel="shadowbox[JTNP]" title="Joshua tree" class="shaddowimages"><img id="JTth" src="media/gallery/jtnp/b_thum/JTthumb.JPG" alt="A small Joshua tree"></a>
至
<a href="media/gallery/jtnp/JT.JPG" rel="shadowbox[JTNP]" title="Joshua tree" class="shaddowimages"><img id="JTth" src="media/gallery/jtnp/s_thum/JTthumb.JPG" alt="A small Joshua tree"></a>
这是我到目前为止所做的,但是当我尝试按下按钮#changethumb 时没有任何反应。
$(document).ready(function() {
var count = 0;
$('#changethumb').click(function() {
if (count === 0) {
$('#shaddowimages img').each(function() {
$(this).attr('src', $(this).attr('src').replace('b_', 's_'));
});
count = 1;
} else {
$('#shaddowimages img').each(function() {
$(this).attr('src', $(this).attr('src').replace('s_', 'b_'));
});
count = 0;
}
})
});
我可以手动检查并替换每个 src,但是有 20 多个图像,如果可以的话,我希望有一种方法可以自动执行此操作。有什么帮助吗?
最佳答案
使用.attr( attributeName, function(index, attr) )
$('#shaddowimages img').attr('src', function (i, old) {
return old.replace('b_', 's_');
});
或者更好地使用.prop( propertyName, function(index, oldPropertyValue) )
$('#shaddowimages img').prop('src', function (i, old) {
return old.replace('b_', 's_');
});
关于javascript - 如何替换 JQuery 属性中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19828643/