[英]Adding items into an array - Separately
目标:单击一个按钮,然后将成分作为单独的项目添加到阵列中。
当前设置:
<% currentUser.ingredients.forEach(function(items){ %>
<p class='ingredients'> <%= items %> </p>
<% }) %>
这给出了:蓝莓芒果柠檬汁
然后,我希望能够通过单击按钮将成分作为单独的项目添加到数组中:
var allIngredients = []
$("#makeList").click(function() {
allIngredients.push($(".ingredients").text())
console.log(allIngredients)
});
此印刷品[“蓝莓芒果柠檬汁”]
问题是,所有一项都不是单独的项。
我需要更改哪些内容才能将它们分开?
您需要遍历$('.ingredients')
var allIngredients = [];
$("#makeList").click(function() {
$(".ingredients").each(function() {
allIngredients.push($(this).text());
});
console.log(allIngredients);
});
如果值可以是多字,仅在文本节点上进行拆分或循环将无法获得预期的结果。 为了获得可靠的解决方案,请在渲染值周围加上一些html标签
<% currentUser.ingredients.forEach(function(items){ %>
<p class='ingredients'> <span class="ingredient"><%= items %></span> </p>
<% }) %>
var allIngredients = []
$("#makeList").click(function() {
$(".ingredients").find('.ingredient').each(function() {
allIngredients.push($(this).text());
});
console.log(allIngredients)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.