2017-08-02 51 views
1

我試圖在其最左邊的列中使用複選框創建一個HTML表格。我希望能夠通過單擊<tr>元素上的任意位置來選擇複選框。我已經得到它的工作,但我當我點擊複選框本身,它不會改變狀態。我已經在Firefox 54中測試過了(我不關心其他瀏覽器)。事件冒泡和JavaScript複選框的問題

我做了一個示範的jsfiddle我的問題https://jsfiddle.net/a92to0tu/

let table = document.querySelector("table"); 
 
table.addEventListener("click", function(e) { 
 
    e.preventDefault(); 
 
    let tr = e.target.closest("tr"); 
 
    let checkbox = tr.firstElementChild.firstElementChild; 
 
    
 
    // This doesn't work 
 
    checkbox.checked = !checkbox.checked 
 
    
 
    // This works but I don't like it 
 
    // setTimeout(function() { 
 
    // checkbox.checked = !checkbox.checked 
 
    // }, 100); 
 
});
<table> 
 
    <tr> 
 
<td><input type="checkbox"></td> 
 
<td>Click works here too</td> 
 
    </tr> 
 
    <tr> 
 
<td><input type="checkbox"></td> 
 
<td>Click works here too</td> 
 
    </tr> 
 
</table> 
 

 
<p>I can click the text/table row, but clicking the checkbox no longer works</p>

+0

檢查,如果點擊的元素是一個複選框 - 參見[更新小提琴(https://jsfiddle.net/a92to0tu/1/) –

+0

請不要在其他地方張貼代碼。鏈接腐爛,請參閱[*如何創建一個最小的,完整的和可驗證的示例*](https://stackoverflow.com/help/mcve).. – RobG

+2

修復是'if(e.target!==複選框) 複選框.checked =!checkbox.checked'在你的小提琴中。 'e.preventDefault()'是不必要的。 –

回答

1

您需要設置一個條件,以確保點擊不是指定複選框:

if(e.target !== checkbox) { 

let table = document.querySelector("table"); 
 
table.addEventListener("click", function(e) { 
 
    let tr = e.target.closest("tr"); 
 
    let checkbox = tr.firstElementChild.firstElementChild; 
 
    
 
    if (e.target !== checkbox) { 
 
checkbox.checked = !checkbox.checked 
 
    } 
 
});
<table> 
 
    <tr> 
 
<td><input type="checkbox"></td> 
 
<td>Click works here too</td> 
 
    </tr> 
 
    <tr> 
 
<td><input type="checkbox"></td> 
 
<td>Click works here too</td> 
 
    </tr> 
 
</table> 
 

 
<p>I can click the text/table row, but clicking the checkbox no longer works</p>

2

使用標籤元素,則根本不需要任何腳本。

table {border-collapse: collapse;} 
 
td { border: 1px solid #999999;}
<table> 
 
    <tr><td><input type="checkbox" id="foo" name="foo"> 
 
     <td><label for="foo">Works here too!</label> 
 
     <td><label for="foo">Works here three!</label> 
 
</table>

+0

這不是我想要的。我最小的例子並沒有表達,但我希望''中的任何單元切換複選框。 – runfalk

+0

然後在所有單元格中添加一個標籤。 ;-) – RobG