当我克隆 div 时,我试图仅更改 label
标记。当前的 JS 代码更改了下拉列表中的产品名称。
var clone = $('#product-1').clone(false)[0].outerHTML.replace(/1/g, counter);
<div class="activeingredients">
<div class="products" id="product-1">
<label>Active Ingredient 1</label>
<ul>
<li style="display:inline-block">
<select name="productid">
<option>Product 1</option>
</select>
</li>
</ul>
</div>
</div>
谢谢
最佳答案
有多种方法可以做到这一点,包括只用一个没有数字的字符串来替换标签文本。但是,根据您已有的内容,我进行了以下更改:
我首先在标签中添加了一个类,以便于选择。您当前的代码选择 div 内的所有数字。
<label class="ingredientLabel">Active Ingredient 1</label>
其次,我克隆了 div。然后选择 .ingredientLabel 内的 html 并使用正则表达式更改数字。我更改了正则表达式以查找字符串内的任何数字,而不仅仅是“1”,以防数字因某种原因发生变化。
$(document).ready(function(){
var counter = 1;
$("#addproduct").click(function(){
counter+= 1;
var clone = $('#product-1').clone(false);
clone.find(".ingredientLabel").html(clone.find(".ingredientLabel").html().replace(/[0-9]+/g, counter));
$(clone).appendTo(".activeingredients")
});
});
这是工作 fiddle :JSFiddle
关于javascript - 将成分 1 更改为 "Ingredient"+ 计数器的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25263081/