Javascript: get element's current “onclick” contents

扶醉桌前 提交于 2019-11-30 07:55:07

问题


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

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

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


回答1:


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

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

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




回答2:


You should try:

document.getElementById('test').onclick



回答3:


You can use Javascript on anchor tag like:

<script type="text/javascript">

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

</script>

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


来源:https://stackoverflow.com/questions/3253770/javascript-get-elements-current-onclick-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!