2017-06-07 6 views
0

私はちょうど2つの単純なボックスを作成しようとしており、1つのボックスからデータを選択して2つ目のボックスにコピーするようにしています。 2番目のボックスにすでに同じものがある場合は、単純なテキストを後ろに追加します。outerHTMLをjQueryオブジェクトとして扱う

基本的には、アイテムが2番目のボックスにないときに機能します。しかし、そうであれば、テキストにデータを追加することはできません。

ここに簡単な例があります。最初の時間をクリックする

https://jsfiddle.net/9mbgw20e/5/

<div id="inventory"> 
    <div class='item'> 
    <span>Apple</span> 
    </div> 
    <div class='item'> 
    <span>Pear</span> 
    </div> 
</div> 
<hr> 
<div id="selected"> 

</div> 


// bring the items from inventory to selected 
// if selected is found, add some text to the back of it 

$('.item').on('click', function() { 
    var h = $(this)[0].outerHTML; 

    var found = false; 
    var foundId = ''; 
    if ($('#selected').children().length < 1) { 
    // if there's nothing selected, just straight add this 
    return $('#selected').prepend(h); 
    } 

    $('#selected').children().each(function() { 
    if ($(this).find('span').text() == $(h).find('span').text()) { // if there is already one in selected div 
     console.log('Found duplicated.'); 
     found = true; 
     foundId = $(this)[0].outerHTML; 
    } 
    }); 

    if (!found) { 
    // if item is not in selected div, add 
    $('#selected').prepend(h); 
    } else { 
    // if item is in selected div, add some text to it 
    $(foundId).append('1, '); 
    } 
}); 

は動作しますが、それをもう一度クリックした後、何も起こりません。

答えて

1

変更が更新されたコードは、スタックオーバーフローにここにいたならば、それは良いことではないでしょう。このfoundId = $(this);

JSFiddle

0

代わりfirst()方法を使用してみてください:

foundId = $(this).first(); 

Updated JSFiddle

+0

にfoundID? –

+0

@MikeMcCaughanです。私が変更したのは、 'foundId'が割り当てられている行だけです。 –

+0

返信いただきありがとうございます!私はすでに各子ノードを反復しているので、 'first();'を追加する理由はありますか?ありがとうございました! – MrYanDao

関連する問題