2015-10-06 59 views
0

我有p元素遍歷,每個選中的輸入影響未選中輸入

<div id="wrapper"> 
    <p><input name="product" type="checkbox"> Unchecked </p> 
    <p><input name="product" type="checkbox"> Unchecked </p> 
    <p><input name="product" type="checkbox"> Unchecked </p> 
    <p><input name="product" type="checkbox"> Unchecked </p> 
    <p><input name="product" type="checkbox"> Unchecked </p> 

    <input type="submit" value="submit" id="submit"> 
</div> 

但是如果我檢查了3複選框,例如它會影響第一和第二

$('#submit').on('click', function() { 
    $('#wrapper p').each(function() { 
     if ($('input[type=checkbox]').is(':checked')){ 
      $(this).text($(this).text().replace("Unchecked", "Checked")); 
     } 
    }); 
}); 
內的複選框列表

我認爲這是因爲它發現一個被檢查過的所有先前的複選標記,但我不知道如何解決這個問題。

小提琴:http://jsfiddle.net/pt9w8ksf/1/

回答

1

輸入標籤是你的段落的後代,所以你必須遍歷DOM樹。您必須使用this,然後找到最近的複選框。

$('#submit').on('click', function() { 
    $('#wrapper p').each(function() { 
     if ($(this).find('input[type=checkbox]').is(':checked')){ 
      $(this).text($(this).text().replace("Unchecked", "Checked")); 
     } 
    }); 
}); 

http://jsfiddle.net/pt9w8ksf/3/

1

你是非常接近:

http://jsfiddle.net/23xwhh3b/

你只需要添加, this到下面的語句,像這樣:

if ($('input[type=checkbox], this).is(':checked')){

jQuery選擇器可以採用第二個參數,它指定上下文第一個參數(選擇器)應該被約束。

在這種情況下,我們希望input[type=checkbox]選擇器限制爲當前上下文(即each()函數中當前處理的p)。

我們可以使用this來引用當前的函數上下文。

$('#submit').on('click', function() { 
    $('#wrapper p').each(function() { 
    if ($('input[type=checkbox]',this).is(':checked')){ 
     $(this).text($(this).text().replace("Unchecked", "Checked")); 
    } 
    }); 
});