简体   繁体   English

element.onclick返回null,element.getAttribute('onclick')不返回

[英]element.onclick returns null and element.getAttribute('onclick') does not

I thought that element.getAttribute('onclick') returns a string-version of whatever element.onclick is set to. 我以为element.getAttribute('onclick')返回的任何element.onclick设置为字符串版本。

var as = document.getElementsByTagName('a');
for(var i=0; i < as.length; i++) {
    // set test to some javascript text
    var test = as[i].getAttribute('onclick');

     // set test to "null"
    var test = String(as[i].onclick);
}

Why is the ".onclick" notation returning null, when the .getAttribute('onclick') shows a value? 当.getAttribute('onclick')显示一个值时,为什么“ .onclick”表示法返回null?

.onclick

returns the function that is bound to the click event. 返回绑定到click事件的函数。

.getAttribute('onclick')

returns the string value of the attribute. 返回属性的字符串值。

In plain HTML, if the code of the attribute is invalid, there is no click event defined and the first will return null. 在纯HTML中,如果属性的代码无效,则没有定义click事件,并且第一个事件将返回null。

In any case, the two will not return the same thing. 无论如何,两者将不会返回相同的东西。 The first returns a function , the second a string . 第一个返回一个function ,第二个返回一个string

By as[i].getAttribute('onclick') you are getting value of attribute named "onclick" in element dom. 通过as[i].getAttribute('onclick')您将在元素dom中获取名为“ onclick”的属性的值。 It is used to get any existing attribute and not specific to onclick 它用于获取任何现有属性,而不特定于onclick

and function as[i].onclick is used to define event, not to get any value. 和函数as[i].onclick用于定义事件,而不是获取任何值。

Basic use of onclick : onclick基本用法:

as[i].onclick=function() {

   console.log('print when clicked');

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当属性具有值时element.getAttribute()返回null - element.getAttribute() returns null when attribute has value element.getAttribute 不是函数 - element.getAttribute is not a function 如何获得element.onclick在Firefox中工作? - How do I get element.onclick working in Firefox? 窗口加载后element.onclick事件在javascript中不起作用 - element.onclick event after window load not working in javascript HTML更改为element.setAttribute(“onclick”,“alert(&#39;Test&#39;);”)和element.onclick =“alert(&#39;Test&#39;);”; - HTML changes with element.setAttribute(“onclick”,“alert('Test');”) and element.onclick = “alert('Test');”; Element.getAttribute() 将 promisestatus 返回为待处理:protractor - Element.getAttribute() returning promisestatus as Pending : protractor 完美滚动条:element.getAttribute不是函数 - Perfect-scrollbar: element.getAttribute is not a function Internet Explorer 7 element.getAttribute 方法中的错误 - Bug in Internet Explorer 7 element.getAttribute method Element.value 和 Element.getAttribute(&quot;value&quot;) 的区别 - Difference between Element.value and Element.getAttribute("value") 我想在单击时隐藏图像。 当element.onclick不起作用时调用函数 - I want to hide the image when clicked. Calling function when element.onclick not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM