允许 TR 元素上的 onclick 事件但阻止复选框中的事件

Allow onclick event on TR element but prevent the event in the checkbox

如何允许 TR 元素上的 onClick 事件但阻止复选框中的事件? 复选框是 table 中 TR 的 TD 的子项。

我在这个问题上所做的是在所有 TD 上添加 onClick,但不在复选框的 TD 上。

这个问题有更好的方法吗?

<tr key={item._id} id={item._id} className={(item.status == "unread")? "unread":""}>
    <td className="inbox-small-cells">
        <input type="checkbox" className="mail-checkbox" />
    </td>
    <td className="view-message  dont-show" onClick={this.viewMsg.bind(this,item.sender)}>{item.sender} {(item.category.length > 0)? 
                        <span className="label label-info pull-right">{item.category}</span>:""}</td>
    <td className="view-message " onClick={this.viewMsg.bind(this,item.sender)}>{item.subject.trunc(40)}</td>
    <td className="view-message  inbox-small-cells" onClick={this.viewMsg.bind(this,item.sender)}>{(item.attachments.length > 0) ? <i className="fa fa-paperclip"></i> : ""}</td>
    <td className="view-message  text-right" onClick={this.viewMsg.bind(this,item.sender)}>{item.createdAt}</td>
</tr>

您可以使用 event.stopPropagation() 调用 tds/checkboxes 将事件传播到 dom 树中的父级。

改为:

<tr key={item._id} id={item._id} onClick={this.viewMsg.bind(this,item.sender)} className={(item.status == "unread")? "unread":""}>
    <td className="inbox-small-cells" onClick={this.stopEventProp(event)}>
        <input type="checkbox" className="mail-checkbox" />
    </td>
    <td className="view-message  dont-show">{item.sender} {(item.category.length > 0)? 
                        <span className="label label-info pull-right">{item.category}</span>:""}</td>
    <td className="view-message ">{item.subject.trunc(40)}</td>
    <td className="view-message  inbox-small-cells">{(item.attachments.length > 0) ? <i className="fa fa-paperclip"></i> : ""}</td>
    <td className="view-message  text-right">{item.createdAt}</td>
</tr>

现在你必须把这个方法放在你的class中:

stopEventProp(e){
  e.stopPropagation();
}

就像大家已经说过的那样event.stopPropagation(). We can also use CSS property pointer-events:none or attribute disabled:true. The following Snippet has 2 working examples using .css() and .attr()

片段

// Option #1
$('.mail-checkbox1').css('pointer-events', 'none');


// Option #2
$('.mail-checkbox2').attr('disabled', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <div class="inbox-small-cells">
    <label>Control #0 (Normal test case)</label>
    <input type="checkbox" class="mail-checkbox0">
    <br/>

    <label>Option #1 (pointer-events:none)</label>
    <input type="checkbox" class="mail-checkbox1">
    <br/>


    <label>Option #2 (disabled: true)</label>
    <input type="checkbox" class="mail-checkbox2">
    <br/>
  </div>
</section>