gpt4 book ai didi

javascript - 如何用 foreach/each 替换相同的类名?

转载 作者:行者123 更新时间:2023-12-01 02:12:23 24 4
gpt4 key购买 nike

我必须将纯文本网址转换为 <a href=""></a> 。我找到了一个有效的 JS 代码。我的问题是我的 HTML 结构需要修改代码,将当前代码放入 foreach 中。

我的html:

<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>

JS:

$(function()
{
var re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/ig;
$('.content').html($('.content').html().replace(re, '<a href="$1" title="">$1</a>'));
});

上面的 JS 可以工作,但是会用相同的内容填充所有的 div。我尝试将此代码放入 foreach 但失败了。我糟糕的 JS 知识让我问这个问题。

您能否提供一些有关如何将此代码放入 foreach 循环中的线索?

最佳答案

.html 这样的函数允许传递函数。然后在内部完成 .each 循环,此外您还可以获得传递的当前值:

$('.content').html(function(i, current) {
return current.replace(re, '<a href="$1" title="">$1</a>');
});

关于javascript - 如何用 foreach/each 替换相同的类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14587460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com