gpt4 book ai didi

javascript - 和 上的事件 onclick

转载 作者:数据小太阳 更新时间:2023-10-29 05:01:04 25 4
gpt4 key购买 nike

我在 <td> 上的表中都有一个 onclick 事件和 <tr>元素。我需要当用户点击特定列( <td> )时, <tr>事件不会被触发,只有 <td>一个。

怎么做?

示例:

HTML:

<tr onclick='trclick();'>
<td>Column 1</td>
<td>Column 2</td>
<td onclick='tdclick();'>Column 3</td>
</tr>

JS:

function trclick(){console.log('tr clicked')};
function tdclick(){console.log('td clicked')};

当用户点击“第 3 列”时,两个事件都会被触发,但我只想要 tdclick()被触发。

最佳答案

您需要做的是在单击子项时停止父事件的传播,这在 jQuery 中很容易完成,但天真地您需要做更多的工作:

function trclick(){
console.log('tr clicked')
};

function tdclick(e){
if (!e) var e = window.event; // Get the window event
e.cancelBubble = true; // IE Stop propagation
if (e.stopPropagation) e.stopPropagation(); // Other Broswers
console.log('td clicked');
};

请注意,对于 Firefox,您需要传递一个 event 参数:

<td onclick='tdclick(event)'>Column 3</td>

关于javascript - <td> 和 <tr> 上的事件 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32404185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com