javascript .onclick不起作用

时间:2018-06-27 15:55:26

标签: javascript html

当用户单击<img class="gallery_image">时,我试图触发一个功能,但是它不起作用。

脚本位于正文的最底部:

<script>

    document.getElementsByClassName('gallery_image').onclick = function (event) {
        console.log('click')
        event = event || window.event;
        var target = event.target || event.srcElement,
            link = target.src ? target.parentNode : target,
            options = {index: link, event: event},
            links = this.parentNode.getElementsByTagName('a');
        blueimp.Gallery(links, options);
    };

</script>

表中有<img>个元素。

<img class="gallery_image" src="...IMG_20170907_192537_A1rqcbg.jpg.230x200_q85_crop.jpg" alt="">

单击此类图像不会执行任何操作(不会将任何内容登录到控制台)。你知道为什么吗?

4 个答案:

答案 0 :(得分:3)

如文档所述,getElementsByClassName()返回一个数组。

使用:

document.getElementsByClassName('gallery_image')[0].onclick

,如果它们是多个元素,则使用forEach

由于该方法的返回值是Array-like而不是Array的实例,因此您可以在其上循环:

const matches = document.getElementsByClassName('example');

Array.from(matches).forEach((x) => {
  x.style.backgroundColor = 'red';
});
.example {
  height: 10px;
  width: 10px;
  margin-top: 5px;
}
<div class="example">
</div>

<div class="example">
</div>

<div class="example">
</div>


文档中的示例:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="parent-id">
        <p>hello word1</p>
        <p class="test">hello word2</p>
        <p >hello word3</p>
        <p>hello word4</p>
    </div>
    <script>
        var parentDOM = document.getElementById("parent-id");

        var test=parentDOM.getElementsByClassName("test");//test is not target element
        console.log(test);//HTMLCollection[1]

        var testTarget=parentDOM.getElementsByClassName("test")[0];//here , this element is target
        console.log(testTarget);//<p class="test">hello word2</p>
    </script>
</body>
</html>

答案 1 :(得分:0)

这是因为getElementsByClassName总是返回一个数组 因此,要访问该数组对象,必须使用

这样的语法
document.getElementsByClassName('gallery_image')[0].onclick = function(){
//your function goes here
}

这里0是document.getElementsByClassName('gallery_image')返回的数组元素

在dom准备就绪后始终执行此类功能

答案 2 :(得分:0)

请与EventTarget#addEventListener一起使用Element#querySelectorAll

document.querySelectorAll('.gallery_image').forEach(element => element.addEventListener(galleryImageClick));

function galleryImageClick(event) {
  console.log(click);
  // do the rest
}

如果要选择一个特定元素,请使用document.querySelector,因为它返回对Node而不是NodeList的引用:

document.querySelector('.gallery_image').addEventListener(galleryImageClick);

如注释中所述,您需要在建立事件侦听器之前确保DOM已准备就绪。您需要为此添加一个适当的事件侦听器:

// vanilla JS way
document.addEventListener('DOMContentLoaded', () => {
  // query the DOM, add event listeners, etc.
});

// or jQuery way
$(document).ready(() => {
  // query the DOM, add event listeners, etc.
});

希望有帮助。

请注意,为什么assigning value to "onclick" property of an element is a bad practice。干杯!

答案 3 :(得分:0)

有一种更简单有效的方法来处理多个节点的点击事件,称为 Event Delegation

  • 在需要侦听click事件的一组元素中找到一个父元素。

  • 将click事件注册到该父元素。现在,无论何时单击子元素,父元素都会听到事件,然后调用回调函数。无需#ids,.classes和[names]即可找到被单击的节点,因为将其注册到事件后,它可以利用事件对象属性event.target

我注意到您可能不知道诸如getElementsByClassNamegetElementsByName getElementsByTagNamequerySelectorAll children之类的方法的返回等。这些属性和方法返回称为HTMLCollectionNodeList类似数组的对象。要正确处理这种类型的数据结构,需要通过数组方法或for循环将每个项目循环。


第一个函数侦听图像上的click事件,然后将其放大或缩小。第二部分将所有图像收集到NodeList中,然后为其URL分配索引号。

演示

// Reference the parent node
var gallery = document.getElementById('gallery');

// Register the parent to the click event
gallery.onclick = zoomImg;

// Callbak function
function zoomImg(e) {

  // if the clicked element is an IMG tag
  if (e.target.tagName === "IMG") {

    // Add/Remove the .zoom class 
    e.target.classList.toggle('zoom');
  }
  return false;
}

// Collect all .image classes into a NodeList
var images = document.querySelectorAll('.image');

/* Loop the NodeList through the forEach() method
|| On each loop add an index number to each of the images' src
*/
images.forEach(function(img, idx) {
  img.src = `http://via.placeholder.com/50?text=${idx+1}`;
});
.image {
  transform: scale(1);
  transition: .5s ease;
}

.zoom {
  transform: scale(2);
  transition: .5s ease;
}
<section id='gallery'>
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
  <img class='image' src="http://via.placeholder.com/50?text=">
</section>