我正在尝试替换jQuery中的IMG路径(注入远程页面)
替换example.com/ thumbs
带有example.com/ images
我已经尝试过,但似乎不起作用。
$("img").attr("src").replace("thumbs", "images");
this 获取值,但不 set 它回到属性:
$("img").attr("src").replace("thumbs", "images");
需要另一个步骤,例如:
var newSrc = $("img").attr("src").replace("thumbs", "images");
$("img").attr("src", newSrc);
或,如果您想要一行:
$("img").attr("src", $("img").attr("src").replace("thumbs", "images"));
看这个,您没有为图像设置SRC。
$(function() {
$('img').each(function() {
$(this).attr('src', $(this).attr('src').replace('thumbs', 'imagessss')); console.log('New src: ' + $(this).attr('src'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/images/thumbs.png" />
var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
这就是您想做的:
var newPath = $("img").attr("src").replace("thumbs", "images");
$("img").attr("src",newPath);
您需要使用返回值更新属性,因为您可以将回调函数用作attr()
方法中的第二个参数,其中第二个参数保留当前属性值。
$('img').attr('src', function(i, src){
return src.replace('thumbs', 'images');
});
如果有多个img
元素,则上述方法将在img
标签上迭代,因此您可以避免使用each()
方法进行迭代。
setTimeout(function() {
$('img').attr('src', function(i, src) {
return src.replace('thumbs', 'images');
});
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://img.pranavc.in/100?t=thumbs" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs1" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs2" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs3" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs4" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs5" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs6" alt="#" />
步骤1:script src =" https://ajax.googleapis.com/ajax/libs/jquery/3.1.1.1/jquery.min.js">
步骤2:
$(document).ready(function(){
$('img').each(function() {
$(this).attr('src', $(this).attr('src').replace('thumbs', 'images'));
console.log('Latest image link ' + $(this).attr('src'));
});
});