表行的 OnClick 事件是否传播到所有包含的元素?
我在 Internet Explorer 下运行的遗留应用程序中遇到了一些有趣的代码。考虑以下几点:
<script type="text/javascript">
function selectRow()
{
var src = window.event.srcElement; // Array of OPTION?!
var rowIndex = src.rowIndex; // Undefined for an OPTION element
highlightRow(rowIndex);
}
</script>
<table>
<tr onclick="selectRow();">
<td>
<select id="foo">
<option value="baz">baz</option>
</select>
</td>
</tr>
</table>
所以,这就是我被难住的地方。当用户从 SELECT 元素中选择一个项目时,将触发 ONCLICK 事件,并且以下情况为真:
this
计算结果为Window
Window.event.srcElement< /code> 计算为“OPTION”元素数组
- 似乎没有办法从事件处理程序中获取选项的父元素。
我需要能够获取被单击的表行的索引。 (正如您从上面的示例中看到的,旧代码错误地假设 this.rowIndex
计算结果为表的当前行索引。)
我假设这里的罪魁祸首是事件冒泡 /em>。
我愿意接受以最正确的方式纠正此问题的建议。我想到这可能是事件绑定在行上的方式,但我有点怀疑(因为事件仍然会冒泡)。
(FWIW,我没有在任何其他浏览器下尝试过这个,因为我们公司只支持IE。请不要拍摄信使。)
I've run into some interesting code in our legacy application running under Internet Explorer. Consider the following:
<script type="text/javascript">
function selectRow()
{
var src = window.event.srcElement; // Array of OPTION?!
var rowIndex = src.rowIndex; // Undefined for an OPTION element
highlightRow(rowIndex);
}
</script>
<table>
<tr onclick="selectRow();">
<td>
<select id="foo">
<option value="baz">baz</option>
</select>
</td>
</tr>
</table>
So, here's where I'm stumped. When the user selects an item from the SELECT element, the ONCLICK event is firing, and the following are true:
this
evaluates toWindow
Window.event.srcElement
evaluates to an array of 'OPTION' elements- There doesn't seem to be a way to get to the parent element of the options from within the event handler.
I need to be able to get the index of the table row that was clicked. (As you can see from the sample above, the legacy code incorrectly assumes that this.rowIndex
evaluates to the table's current row index.)
I'm assuming that the culprit here is event bubbling.
I'm open to suggestions for correcting this problem in the most correct manner. It occurs to me that it could be the way the event is bound on the row, but I kind of doubt it (since the event would still bubble).
(FWIW, I have not tried this under any other browsers, since our company only supports IE. Please don't shoot the messenger.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的样本中是否遗漏了一些额外的复杂性?因为为什么不只是:
如果这确实是您需要做的全部事情。
Are you missing some additional complexity in your sample? Because why not just:
if that's really all you need to do with it.