如何访问具有相同名称属性的img标签

How to access img tag with the same name attribute

本文关键字:属性 标签 img 何访问 访问      更新时间:2023-09-26

我在HTML代码中有一组图像:

<img name="image[]" />
<img name="image[]" />
<img name="image[]" />`

我想访问所有的,当我点击他们使用JavaScript?谢谢。

var elements = document.querySelectorAll("img[name='image'[']']");
for(var i = 0; i < element.length; i++){
    elements[i].addEventListener("click", someFunc, false);
}
function someFunc(e){
   // you can use the `elements` array to access them all
   // or simply the `this` for the particular element clicked on
   this.src = "http://placehold.it/400x400";
}

一个纯JS解决方案。

Demo

$('name="image''['']"').on('click', function() {
    var this_one = this; // "this" is the clicked one
});

如果没有jQuery,它会像

var img = document.querySelectorAll('[name=image''['']]');
for (var i=img.length; i--;) {
    img[i].addEventListener('click', handler, false);
}
function handler() {
    // "this" is the clicked image
}

小提琴

相关文章: