我有snippet:
jQuery(document).ready(function() {
//First bracket detection
var string = $.trim($('p').text());
string = string.replace(/\(([^)]+)\)/, "<span>$1</span>");
$('p').html(string);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> width (10mm) </p>
<p> width (10mm) </p>
<p> width (10mm) </p>
如您所见,这些项目是重复的。每个项目出现3次,我怎么能只做一次?
答案 0 :(得分:2)
您需要使用.each()
替换其上下文中的段落内容。
jQuery(document).ready(function() {
$('p').each(function() {
//First bracket detection
var string = $.trim($(this).text());
string = string.replace(/\(([^)]+)\)/, "<span>$1</span>");
$(this).html(string);
})
});
span {
font-size: 30px;
color: green;
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>width (10mm)</p>
<p>width (10mm)</p>
<p>width (10mm)</p>