我想要一个用图像替换每个 li 的函数。这是我的代码:
$(document).ready(function(){
var tmphref;
var tmpname;
var str = '<a href="' + tmphref + '"><img src="http://www.somesite.com/a/' + tmpname[1] + '/avatar-small.jpg /></a>';
$('#somediv li a').each(function(){
tmphref = $(this).attr("href");
tmpname = /http\:\/\/(\w+)\.somesite\.com\//.exec(tmphref);
$(this).parent().replaceWith(str);
});
});
图像位于以下特定路径中:www.somesite.com/a/username/avatar-small.jpg
上面的代码不起作用。有什么想法吗?
提前谢谢您。
最佳答案
移动
var str = '<a href="' + tmphref + '"><img src="http://www.somesite.com/a/' + tmpname[1] + '/avatar-small.jpg /></a>';
在tmphref
和tmpname
之后,像这样
$('#somediv li a').each(function(){
tmphref = $(this).attr("href");
tmpname = /http\:\/\/(\w+)\.somesite\.com\//.exec(tmphref);
var str = '<a href="' + tmphref + '"><img src="http://www.somesite.com/a/' + tmpname[1] + '/avatar-small.jpg /></a>';
$(this).parent().replaceWith(str);
});
因为变量 str
已被赋值为 undefined
tmphref
和 tmpname
,因此更改之后的 tmphref
和 tmpname
不会影响变量 str
而且,在这种情况下,您不需要在 .each
函数外部为 tmphref
和 tmpname
声明变量。
关于jQuery:用 .each() 替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2688744/