2015-04-02 128 views
0

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

<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"); 
    }); 

回答

1

你可以通过li元素循环,找到img元素,在src财产做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

参考文献:

+0

谢谢。如果src的原始链接是“img/database1.png”,或者“img/webapp1.png”或者“img/image1.png”,那么该怎么办?我是否可以将所有可能的不同单词替换为src =“ IMG/mobile1.png”。问题是我不知道原始单词是“数据库还是网络应用程序或图像”,或者它可能是任何单词 – user21 2015-04-02 00:50:25

+0

如果您不是100%确定哪些文本会出现,那么您最好使用正则表达式,但知道它会以数字结尾。 http://stackoverflow.com/questions/3890680/jquery-regex-replace-from-select-text – silencedmessage 2015-04-02 00:52:17

+0

我试过但不能。我使用这个吗? (“src”,img.prop(“src”)。replace(/ [\ d。] * /,“mobile”)); – user21 2015-04-02 00:58:33

3

这将替换所有字符在src文件名上升到第数字与“移动” (如上所述)#portfolio>li>img

$("#portfolio>li>img").each(function() { 
    $(this).attr("src", $(this).attr("src").replace(/[^\/]*?(?=\d*\.png)/, "mobile")); 
}); 
+0

谢谢。我试过了,它只在代码替换时才起作用(/.*?(?= \ d +)/,“img/mobile”));有没有一种方法,我只需要在img /和数字之前替换单词? – user21 2015-04-02 01:19:50

+0

谢谢。有用。/[^ \ /]是否表示查找任何不是'\'的字符? – user21 2015-04-02 01:37:46

+0

差不多!它是“任何不是'/'的字符”。它必须被转义,因为'/'是正则表达式的开始/结束字符。 – 2015-04-02 01:39:31