我试图用一个限制替换一个字符串,但我不知道。有人,请帮助我。这是问题所在:
请看上面的div,我想把dummy换成dummy2,但不超过2个,我可以把dummy换成dummy2,但不限制全部换,
我的代码
// replace with title
var get_parent = $('.single-cat-product-item');
if (get_parent.length > 0) {
get_parent.each(function() {
var get_titile = $(this).find('.single-cat-product-list-title h3').justtext();
var az_link = $(this).find('.Check-Latest-Price-On-Amazon').attr('href');
var item_content = $(this).find('p');
item_content.each(function(i) {
var finalOutput = $(this).html().replace(new RegExp(get_titile, "ig"), '<a href="' + az_link + '" rel="nofollow">' + get_titile + '</a>');
$(this).html(finalOutput);
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="single-cat-product-item">
<h3 class="single-cat-product-list-title"> Dummy2 </h3>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy </p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy </p>
</div>
有谁能给我解决办法,只限制两次?
最佳答案
i
是您的索引。使用它:
item_content.each(function(i) {
if (i < 2) {
var finalOutput = $(this).html().replace(new RegExp(get_titile, "ig"), '<a href="' + az_link + '" rel="nofollow">' + get_titile + '</a>');
$(this).html(finalOutput);
}
});
看到它在这里工作:
$(window).on('load', function() {
var get_parent = $('.single-cat-product-item');
if (get_parent.length > 0) {
get_parent.each(function() {
var title = $('h3', this).text(),
az_link = $(this).find('.Check-Latest-Price-On-Amazon').attr('href'),
item_content = $(this).find('p');
item_content.each(function(i) {
if (i < 2) {
var finalOutput = $(this).html().replace(new RegExp(title, "ig"), '<a href="' + az_link + '" rel="nofollow">' + title + '</a>');
$(this).html(finalOutput);
}
});
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="single-cat-product-item">
<h3 class="single-cat-product-list-title">Dummy</h3>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy </p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy </p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy </p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy </p>
</div>
关于javascript - 用 jQuery 替换字符串的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51652396/