Why is the onclick event not triggered in this place? If you can get the DOM object of the currently clicked li in jquery, can't it be used in JS like this?
$(document).ready(function(){
$("ul li").click(function(){
console.log($(this));//打印出当前被点击的li的jquery对象
console.log(this);//打印出当前被点击的li的dom对象
});
});
window.onload = function(){
var lis = document.getElementsByTagName("li");
lis.onclick = function(){
console.log("111");
console.log(this);
}
}
Revise:
window.onload = function(){
var lis = document.getElementsByTagName("li");
Array.from(lis).forEach(function(el) {
console.log("111");
console.log(this);
})
}
<p>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</p>
Thank you everyone. I used jquery before, but now I have found many problems when I look at js again. I won’t make this kind of stupid mistake again in the future, I’m very impressed ^_^.
Can you click to trigger this event? I can use segmentFault.
But there is a slight problem with your code. getElementsByTagName returns an array-like object
You should traverse it and then assign the onclick value to each element
is not the reason for
this
.onclick
is a DOM event. But at this timelis
is not dom at all, but a collection of DOM.jQuery can handle it because
$("ul li")
returns a jQuery object. When the click function is called on it, jQuery will implicitly use a loop.Although
lis
looks like an array, it is not an array. So you can use theArray.from
function to turn it into a real array.lis = document.getElementsByTagName("li") gets an array.
How should you bind events?
Try not to use .onclick() to write the click event; use addEventListener('click', function(){console.log(this)}); add the click event and see if it can be triggered. I suspect it is because you got lis Is onclick an array not working for this reason?
The second piece of code is written incorrectly. lis is an array, not a dom object, so setting onclick is useless
Change it to this
Use the method
getElementsByClassName
directly, encapsulategetElementsByTagName
and it can be used as dom operationAs shown in the picture above, your lis is printed as an array of objects. According to your idea, you should traverse lis to bind onclick to each li object