Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何用foreach/each替换为相同的类名?_Javascript_Jquery - Fatal编程技术网

Javascript 如何用foreach/each替换为相同的类名?

Javascript 如何用foreach/each替换为相同的类名?,javascript,jquery,Javascript,Jquery,我必须将纯文本URL转换为。我发现了一个可以工作的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

我必须将纯文本URL转换为
。我发现了一个可以工作的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>'));
});
$(函数()
{
变量re=/(https?:\/\/([-\w\.]+)+(:\d+)(\/([\w/\.]*(\?\S+))))/ig;
$('.content').html($('.content').html().replace(re'));
});
上面的JS可以工作,但将使用相同的内容填充所有div。我试图将此代码放入foreach中,但失败了。我可怜的JS知识让我这么问

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

.html()
用于检索时仅选择第一个匹配的元素。不过,您可以很容易地完成这项工作,因为像
.html
这样的函数可以使用函数参数进行设置,该设置可以逐个迭代每个选定的元素

$(".content").html(function (_, html) {
   return html.replace(re ...etc...);
});

.html
这样的函数允许传递函数。一个
。然后在内部完成每个
循环,并且您可以获得传递的当前值:

$('.content').html(function(i, current) {
  return current.replace(re, '<a href="$1" title="">$1</a>');
});
$('.content').html(函数(i,当前){
返回电流。更换(re);
});

如果我正确理解了您的问题,您需要循环查看每个
.content
div,请尝试以下操作:

$('.content').each(function() {
    var $content = $(this);
    var re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/ig;    
    $content.html($content.html().replace(re, '<a href="$1" title="">$1</a>'));
});
$('.content')。每个(函数(){
var$content=$(此值);
变量re=/(https?:\/\/([-\w\.]+)+(:\d+)(\/([\w/\.]*(\?\S+))))/ig;
$content.html($content.html().replace(re),);
});