jQuery:用 .each() 替换字符串

标签 jquery regex

我想要一个用图像替换每个 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>';

tmphreftmpname之后,像这样

$('#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 tmphreftmpname,因此更改之后的 tmphreftmpname 不会影响变量 str

而且,在这种情况下,您不需要在 .each 函数外部为 tmphreftmpname 声明变量。

关于jQuery:用 .each() 替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2688744/

相关文章:

正则表达式从右侧提取不贪婪

javascript - 这个表达式在 javascript 中是什么意思?

javascript - $(window).width()之后mouseenter被称为指数倍。

php - 在 yii2 中使用 ajax 填充或填充所有字段

javascript - 'duplicate' jQuery 伪类选择器的用途是什么?

javascript - Jquery "refuses"更新CSS?

具有否定模式的 Python 正则表达式

javascript - 仅针对某个范围内的数字动态创建 ng-pattern 的正则表达式

regex - Perl 正则表达式不匹配

java - 修复 java 中交错的正则表达式替换输出