[英]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.