JQuery 替换源文本

JQuery replace src text

如何将所有 ul>li>ing 元素的 src 文本 "web" 替换为 "mobile"? 想把"img/web1.png"改成"img/mobile1.png","img/web2.png"改成"img/mobile2.png","img/web7.png"改成"img/mobile7.png"等等。

<div class="col-md-2">  
      <center><a href="#"><div class="img-circle" id="circle2">Mobile</div></a></center>
      <br/> 
</div>

<div id = "wrapper">
        <ul id = "portfolio">
            <li><img class="img-thumbnail" src="img/web1.png" alt = "img"/></li>
            <li><img class="img-thumbnail" src="img/web2.png" alt = "img"/></li>
            <li><img class="img-thumbnail" src="img/web3.png" alt = "img"/></li>
            <li><img class="img-thumbnail" src="img/web4.png" alt = "img"/></li>
            <li><img class="img-thumbnail" src="img/web5.png" alt = "img"/></li>
            <li><img class="img-thumbnail" src="img/web6.png" alt = "img"/></li> 
            <li><img class="img-thumbnail" src="img/web7.png" alt = "img"/></li> 

            <button id="zoom" type="button" class="btn btn-info"> 
                <span class="glyphicon glyphicon-search"> Zoom </span> 
            </button>
        </ul> 

    </div>

    $("#circle2").click(function(){ 
      $("#portfolio>li").first().children("img").attr("src","img/mobile1.png");
    });

您可以遍历 li 元素,找到 img 元素并在 src 属性.[=18= 上执行 replace ]

$(document).ready(function () {
    $("#circle2").click(function () {

        // Loop through all li elements in the 
        //     element with the id of portfolio
        $("#portfolio").find("li").each(function () {
   
            // Find the image tag
            var img = $(this).find("img");
      
            // Update the src property to the same thing, 
            //       replacing web with mobile
            img.prop("src", img.prop("src").replace("web", "mobile"));

        }); // end li loop
    }); // end change stuff click event
}); // end doc ready

您可以看到一个有效的 JSFiddle here

参考文献:

对于所有 #portfolio>li>img:

,这会将 src 文件名中直到第一个数字的所有字符替换为 "mobile"(根据您上面的评论)
$("#portfolio>li>img").each(function() {
    $(this).attr("src", $(this).attr("src").replace(/[^\/]*?(?=\d*\.png)/, "mobile"));
});