简体   繁体   English

相当于jQuery onclick的Javascript

[英]Javascript equivalent of jQuery onclick

How should i construct my code to get the effect of this jQuery 我应该如何构造我的代码以获得此jQuery的效果

var divQuery = $('.html5gallery-thumbs-0').children();
    divQuery.on('click', function () {...}

I thought it is something like this : 我以为是这样的:

 var divQuery = document.getELementsByClassName('html5gallery-thumbs-0');
        divQuery.onclick = function (elem) {
//this.style.display = 'none'
// OR
//elem.style.display = 'none'

}

Element should reference to the clicket object right? 元素应该引用clicket对象吗? Or it should be the key word this . 或者,它应该是关键单词this I want to learn javascript because jQuery is only library after all. 我想学习javascript因为jQuery毕竟只是库。 Thank you in advance! 先感谢您!

Just catch the parent with querySelector and get it's children with children function. 正好赶上家长与querySelector ,并把它的孩子children的功能。 Then - iterate over it and bind listener. 然后-对其进行迭代并绑定侦听器。

 const divQuery = document.querySelector('.a'); Array.from(divQuery.children).forEach(v => { return v.addEventListener('click', function() { console.log(this.textContent); }) }) 
 <div class="a"> <div>child1</div> <div>child2</div> </div> 

Extending kind users answer with two other approaches: 扩展友善用户的回答还有另外两种方法:

Using the latest and greatest JS features: 使用最新和最强大的JS功能:

const divQuery = document.querySelector('.a');
divQuery.childNodes.forEach(v => {
  v.addEventListener('click', function() {
    console.log(this.textContent);
   })
 });

And a really old one (which supports IE and other older browsers): 还有一个非常古老的版本(它支持IE和其他较旧的浏览器):

const divQuery = document.getElementsByClassName('a')[0];
  [].forEach.call(divQuery.children, function(v){
     v.addEventListener('click', function() {
     console.log(this.textContent);
  })
})

what you are doing is almost correct. 你在做什么几乎是正确的。 But when you are finding elements by class it gives you a collection of object. 但是,当您按类查找元素时,它将为您提供对象的集合。 So, first select the index then assign the onclick function. 因此,首先选择索引,然后分配onclick函数。 Like below. 像下面。

var divQuery = document.getELementsByClassName('html5gallery-thumbs-0');
        divQuery[0].onclick = function (elem) {
//this.style.display = 'none'
// OR
//elem.style.display = 'none'

}

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

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