Javascript:获取元素当前的“onclick”内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3253770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:53:29  来源:igfitidea点击:

Javascript: get element's current "onclick" contents

javascriptonclick

提问by Mala

I have a page with the following code:

我有一个包含以下代码的页面:

<a id="test" href="someurl" onclick="somefunction">link</a>

I need to actually read the 'onclick' data. As such, I would like something to the effect of

我需要实际阅读“onclick”数据。因此,我想要一些效果

alert(document.getElementById('test').onClick)

Sadly, it returns undefined. What do I need to do to get somefunction?

可悲的是,它返回undefined。我需要做什么才能得到somefunction

回答by Faisal

Assuming the tag is well-formed, a tag's attribute can be obtained via Element.getAttribute.

假设标签格式良好,标签的属性可以通过Element.getAttribute.

document.getElementById('test').getAttribute('onclick')
// -> "somefunction"

Hopefully you aren't using onclickfor some unscrupulous purpose like storing data.

希望您不会将其onclick用于诸如存储数据之类的不道德目的。

回答by ketan

You can use Javascript on anchor tag like:

您可以在锚标记上使用 Javascript,例如:

<script type="text/javascript">

  function testClick(id)
  {
     alert(id);
  }

</script>

<a href="#" id="test" onclick="testclick(this.id);">Click</a>

回答by Josiah

You should try:

你应该试试:

document.getElementById('test').onclick.toString()