Sha*_*dor 1 javascript onclick
假设onclick处理程序设置为a <tr>是否可以为一个特定禁用/覆盖它<td>?
<tr onclick='somefunction()'>
<td> </td> <!--onclick should work here-->
...
<td> </td> <!--onclick should not work here-->
...
<td> </td> <!--onclick should work here-->
</tr>
当然,我可以<td>单独为它们设置它,或者将a的名称传递td给函数,并根据这个名称决定做什么,但似乎应该有一个更简单的解决方案.
在somefunction你可以检查cellIndex的td,并提前返回,如果无法点击的细胞已被点击.像这样的东西:
function somefunction (e) {
if (e.target.cellIndex === 1) {return;}
/* Do something, the td is clickable */
}
Run Code Online (Sandbox Code Playgroud)
要使用内联处理程序,您必须传递事件对象:
<tr onclick='somefunction(event)'>
Run Code Online (Sandbox Code Playgroud)
如果你在单元格中有元素,事情就会变得复杂一些.在这种情况下,你必须找到一个td父元素,如下所示:
function somefunction (e) {
var target = e.target; // Cache the target element
while (target) { // Iterate through elements
if (target.tagName === 'TD') { // TD found, stop iteration
break;
}
target = target.parentElement; // Set target as a parent element of the current element
}
if (target === null) {return;} // Check that we really have a TD
if (target.cellIndex === 1) {return;} // A non-clickable cell clicked
:
}
Run Code Online (Sandbox Code Playgroud)
编辑2018
在2018年元素有closest()方法,因此不需要上面的循环,target = e.target.closest('td')将确保td使用a.
一个非常简单的方法是使用CSS pointer-events: none,但遗憾的是,在IE <11的这种特殊情况下,这在FF中不起作用,尽管在Chrome和IE11中运行良好.如果单元格恰好包含交互元素,那么防止指针事件也会很糟糕.
小智 5
我发现最简单的方法是使用<td>标记中的 onclick=event.stopPropagation() 停止将事件传递给父 html 。
所以 <td class=whatever onclick=event.stopPropagation()>cell data<td>