简体   繁体   English

使用javascript queryselectorall而不是jquery选择器

[英]using javascript queryselectorall instead of jquery selector

I want to rewrite this jQuery in pure JavaScript : 我想用纯JavaScript重写此jQuery

var gallery1 = $('.gallery a');

gallery1.click(function(event){
    event.preventDefault();
    console.log('onclick');
});

After trying to figure it out I ended with something like this: 在试图弄清楚之后,我得到了这样的结果:

var gallery = document.querySelector('.gallery a');

gallery.onclick = function(event){
    event.preventDefault();
    console.log('onclick');
};

But it works only with the first anchor of the ul . 但这仅适用于ul的第一个锚点。

When I try to use querySelectorAll('.gallery a') it does nothing. 当我尝试使用querySelectorAll('.gallery a')它什么也不做。

I`m new to JavaScript . 我是JavaScript的新手。 Can someone help me to figure it out? 有人可以帮我弄清楚吗?

HTML HTML

<ul class="gallery" id="gallery">
    <li class="">
        <a href="img/gallery/gallery1.jpg" class="" id="anchor">
            <img src="img/gallery/gallery1.jpg" alt="image 1" class="img">
        </a>
    </li>
    <li class="">
        <a href="img/gallery/gallery2.jpg" class="">
            <img src="img/gallery/gallery2.jpg" alt="image 1" class="img">
        </a>
    </li>
    <li class="">
        <a href="img/gallery/gallery3.jpg" class="">
            <img src="img/gallery/gallery3.jpg" alt="image 1" class="img">
        </a>
    </li>
    <li class="">
        <a href="img/gallery/gallery4.jpg" class="">
            <img src="img/gallery/gallery4.jpg" alt="image 1" class="img">
        </a>
    </li>
    <li class="">
        <a href="img/gallery/gallery5.jpg" class="">
            <img src="img/gallery/gallery5.jpg" alt="image 1" class="img">
        </a>
    </li>
</ul>

You need to handle the array-like nodelist from querySelectorAll() : 您需要从querySelectorAll()处理类似数组的节点列表:

var gallery = document.querySelectorAll('.gallery a');

gallery.forEach(function(item) {
  item.onclick = function(event){
    event.preventDefault();
    console.log('onclick');
  };
});

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM