jQuery的推文阵列 [英] jQuery push text to array
本文介绍了jQuery的推文阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是简单地试图把一个里
元素的文本,当我点击添加按钮。但是,当我点击我的添加按钮,它是推动我的列表到阵列中的所有项目。我想这是因为我只使用一个类。什么是解决这个问题的最好方法?在此先感谢!
HTML
< DIV ID =产品>
< UL>
<李>< P>的Lorem 1< / P><按钮类=目标>添加< /按钮>< /李>
<李>< P>的Lorem 2'; / P><按钮类=目标>添加< /按钮>< /李>
< / UL>
< / DIV>
的jQuery
$(文件)。就绪(函数(){
VAR阵列=阵列();
$(目标)。点击(函数(){
$('P')。每个(函数(I,E){
的Array.push($(E)的.text());
});
的console.log(数组);
});
});
解决方案
$(文件)。就绪(函数(){ 变种数组= []; $(目标)。点击(函数(){
的Array.push($(本).siblings(P)文本()); //这个替换,它会从仅点击了李的文本。
的console.log(数组);
});
});
I'm simply just trying to push the text of an li
element when I click the add button. But when I click my add button, it is pushing all the items in my list to the array. I guess it's because I'm just using a class. What would be the best way around this? Thanks in advance!
HTML
<div id="products">
<ul>
<li><p>Lorem 1</p><button class="target">Add</button></li>
<li><p>Lorem 2</p><button class="target">Add</button></li>
</ul>
</div>
jQuery
$(document).ready(function(){
var array = Array();
$(".target").click(function() {
$('p').each(function (i, e) {
array.push($(e).text());
});
console.log(array);
});
});
解决方案
$(document).ready(function(){
var array = [];
$(".target").click(function() {
array.push($(this).siblings('p').text()); //Replace with this and it will get the text from clicked li only.
console.log(array);
});
});
这篇关于jQuery的推文阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文