2

li追加ボタンをクリックしたときに、要素のテキストをプッシュしようとしているだけです。しかし、追加ボタンをクリックすると、リスト内のすべてのアイテムが配列にプッシュされます。クラスを使っているからだと思います。これを回避する最善の方法は何でしょうか?前もって感謝します!

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);
    });
});
4

3 に答える 3

3

これはどう:

$(document).ready(function(){

    var array = []; //Use the bracket notation instead.

    $(".target").click(function(e) {
        var p = $(this).closest('li').find('p');
        array.push(p.text());

        console.log(array);
    });
});

基本的に、あなたはあなた(クリックされたもの)をli囲む最も近いものを見つけて、それからそれに含まれる段落を見つけたいと思います。.targetli

于 2013-03-25T15:39:56.153 に答える
0
$(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);
    });
});
于 2013-03-25T15:41:29.627 に答える
0

あなたのJavaScriptコードは本質的に次のように言っています:

クラス「target」の要素がクリックされたら、段落要素のテキストのそれぞれを配列にプッシュします

これを置き換えることを検討してください:

$('p').each(function (i, e) {
    array.push($(e).text());    
});

と:

array.push($(this).previousSibling.text());

これにより、代わりに、ユーザーがクリックしたボタンの直前の段落要素からのみテキスト値が追加されます。

于 2013-03-25T15:45:19.857 に答える