Javascript 除了在jQuery中单击选择框外,如何在表单元格中使用单击

Javascript 除了在jQuery中单击选择框外,如何在表单元格中使用单击,javascript,jquery,Javascript,Jquery,有一个包含一些图像和一些选择框的表格。每当用户单击该行时,我想突出显示该行。该行表示除选择框和图像之外的任何td 现在我用这个, $("selector").live("click",function() { $(this) .parents("tr:first") .toggleClass("diffColor") ; }); 但是如果我点击选择框或图片,它会应用这个类。但是当我点击选择框或任何其他图片时,我不需要 看这里 提前感谢…试试这个

有一个包含一些图像和一些选择框的表格。每当用户单击该行时,我想突出显示该行。该行表示除选择框和图像之外的任何td

现在我用这个,

$("selector").live("click",function() {
    $(this)
        .parents("tr:first")
        .toggleClass("diffColor")
    ;
});
但是如果我点击选择框或图片,它会应用这个类。但是当我点击选择框或任何其他图片时,我不需要

看这里

提前感谢…

试试这个

$("td").live("click",function() {
$(this)
    .parents("tr:first")
    .toggleClass("diffColor")
;
});
试试这个:

$(".selector").on("click", function (e) {
    if (e.target === this) $(this).parent("tr:first").toggleClass("diffColor");
});
假设.selector是所有td的类名

这里,这意味着当前范围中的元素,它始终是此处单击的td

e.target表示实际单击的元素,可以是td、checkbox或td中的任何内容

因此,如果实际单击的元素不是当前范围内的td,e.target==此返回值为false,且不发生任何事情,则不会触发任何单击事件,反之亦然。

如果在单击包含或的td时不想切换类,则可以执行以下操作:

$('selector').live('click', function() {
    if (!$(this).has('select, img').length) {
      $(this).parents('tr:first').toggleClass('diffColor');
    }
});

这对你合适吗?只需将类更改添加到td

$("#tableId td.change").on("click",function() {
        $(this)
            .parents("tr:first")
            .toggleClass("diffColor")
        ;
    });


<table id="tableId" border="1">
     <thead>
        <th></th>
        <th>First</th>
        <th>Second</th>
        <th>Third</th>
     </thead>
     <tbody>
        <td><input type="checkbox"/></td>
        <td class="change">FirstTableColumn1</td>
        <td class="change">FirstTableColumn2</td>
        <td><select>
            <option>AAA</option>
            <option>BBB</option>
            <option>CCC</option>
            <option>DDD</option>
            </select></td>

     </tbody>
   </table>

这是因为您的事件正在冒泡

您可以为子项上的单击事件添加event.stopPropagation以防止出现这种情况

因此,对于任何输入和选择元素,添加以下内容以防止传播。如果已经有了用于单击的事件处理程序,请在函数的开头添加StopRopAgation

$("#tableId").find("input, select")
             .click(function(e){e.stopPropagation();});

我有办法检查TD是否包含图像或选择框

$("#tableId td").on("click",function() {  
     var ths=$(this);    
     if((ths.has("select").length ? false : true)&&(ths.has("img").length ? false : true)){
         $(this).parent().toggleClass("diffColor");
     }
    });

你能提供小提琴吗?请稍等2分钟。我会为你提供缺少的小提琴。在你的$'selector'中?我只是在说selector。我把我的代码@Dolours放在这里,它对我有效。非常感谢。我从过去2小时开始工作。这个问题对于嵌套元素来说很常见,这是一个简单的解决方案。但是,如果有一个嵌套元素而不是select或img,会发生什么?toggleClass不会出现..实际上这一个比我的答案好。检查特定的td是否包含任何img或选择标记(如果存在),dn不切换类,否则添加相同的。