如何替换属性 JQuery 中的子字符串

How to replace a substring within an attribute JQuery

本文关键字:JQuery 字符串 属性 何替换 替换      更新时间:2023-09-26

在过去的几个小时里,我一直在寻找一种方法来做到这一点,但一无所获。我正在尝试找出一种仅更改属性中的子字符串的方法。我想做的一个例子是改变

<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+ 张图像,如果可以的话,我想要一种方法来自动化它。有什么帮助吗?

use .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_');
});

Read .prop() vs .attr()

可以在attr内运行所有逻辑,因此您不必在'if中复制代码

 $('#changethumb').click(function() {
    $('#shaddowimages img').attr('src', function (i, src) {
         var newSrc= count==1 ? src.replace('b_', 's_') : src.replace('s_', 'b_');
         count=  count == 1 ? 10 : 1;
          return  newSrc;
    });
 });

似乎很奇怪,count只有 1 或 10。复制了您的代码,但没有意义