我正在尝试将一个字符串替换为一个限制,但我不知道。有人请帮帮我。这是问题所在:
请在div上方查看,就像我想用dummy2更改哑元,但不超过2,我能够将哑元替换为哑元2,但不能限制全部替换,
我的代码
// 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>
任何人都可以给我解决方案以限制两次吗?
答案 0 :(得分:1)
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>