如何使用Javascript获取调用者元素? [英] How to get caller element using Javascript?

查看:192
本文介绍了如何使用Javascript获取调用者元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张ID为tbl的表,它有2行3列。每个单元格(td)都有一个明确定义的ID。此外,该表还有一个调用函数foo()的onclick事件。每当单击单元格时,都会生成onclick()。
表标记是


< table id =tblwidth =80%height =20%onclick =javascript:foo()>


我也尝试过 javascript:foo(this)



我想找出被点击的表格单元格的id。



我尝试了以下javascript

  function foo(e)
{
var sender =(e && e.target)|| (window.event && window.event.srcElement);
alert(Sender+ sender.id);
}

这在Google Chrome和IE中非常有用,但在Firefox中不起作用。在Firefox中,发件人是未定义的。
如何在Firefox中获取调用者单元格?

解决方案

首先,删除 javascript:来自 onclick 属性。您在链接的 href 属性中将javascript与javascript混淆。在Javascript代码中, javascript:会创建一个标签,名为javascript。



除此之外, foo(event)应该能够正确处理最终的JavaScript代码示例。它在Firefox中无效但在Chrome和IE中运行的原因是;它们都支持全局事件对象 window.event (当 e.target 产生<$ c时$ c> undefined ,因为这个是一个没有 target 属性的元素)。 Firefox不支持全局事件对象。



进一步阅读:


I have a table with id "tbl" and it has 2 rows and 3 cols. Each cell(td) has an explicitly defined id. Also, the table has an onclick event that calls a function foo(). The onclick() would be generated whenever any cell is clicked. The table tag is

< table id="tbl" width="80%" height="20%" onclick="javascript: foo()" >

I also tried javascript:foo(this)

I want to find out the id of the table cell that was clicked.

I have tried the following javascript

function foo(e)
{
    var sender = (e && e.target) || (window.event && window.event.srcElement);
    alert("Sender" + sender.id);
}

This works great in Google Chrome and IE, but not in Firefox. In Firefox, sender is undefined. How to get the caller cell in Firefox?

解决方案

Firstly, remove javascript: from the onclick attribute. You're confusing this with javascript in the href attribute of a link. In Javascript code, javascript: would create a label named "javascript".

Other than that, foo(event) should work correctly with your final JavaScript code sample. The reason it doesn't work in Firefox but does in Chrome and IE is; they both support the global event object, window.event (which is evaluated when your e.target yields undefined, because this is an element which will not have a target property). Firefox doesn't support the global event object.

Further reading:

这篇关于如何使用Javascript获取调用者元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆