如何从调用的函数中引用包含事件的元素?
在 fireAlert()
函数内部,如何引用调用它的元素,而不必通过链接将 this
作为参数传递?
<script type="text/javascript">
//function
function fireAlert(){
alert();
}
</script>
<a href="javascript:;" onclick="fireAlert();">Fire</a>
From inside of the fireAlert()
function, how can I reference the element that called it, without having to pass this
as an argument through the link?
<script type="text/javascript">
//function
function fireAlert(){
alert();
}
</script>
<a href="javascript:;" onclick="fireAlert();">Fire</a>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有更简单的方法可以使用 jQuery 来完成此操作,但如果没有它,这是如何完成的:
更新: 请尝试以下 HTML/Javascript 代码。 请注意我如何将 onclick 事件附加到 window.onload 内部,而不是将其指定为元素的属性。
对于本示例,我将事件附加到页面中的所有锚标记,但您可以将特定锚标记的
getElementsByTagName
替换为getElementById
。There are easier ways of doing this with jQuery,but this is how it's done without it:
UPDATE: Please try the following HTML/Javascript code. Notice how I am attaching the onclick event inside of window.onload instead of specifying it as an attribute at the element.
For this example, I'm attaching the event to all anchor tags in the page, but you could replace
getElementsByTagName
withgetElementById
for a specific one.正如 Jose 所说,使用 jQuery 会很容易。
As Jose said, it would be easy with jQuery.