简体   繁体   English

尝试将属性“onclick”添加到由javascript函数创建的html“img”元素

[英]Trying to add attribute “onclick” to a html “img” element created by javascript function

This is part of a function that is creating a table with images and the name of the image inserted by the user.这是创建包含图像和用户插入的图像名称的表的函数的一部分。

var NameFile = [];//Where the names of the files are stored

Function handleFiles() {
var inputElement = document.getElementById("input");
var fileList = inputElement.files; 

for(var i = 0; i < fileList.length; i++){

NameFile.push(fileList[i].name);
var Img = document.createElement("tr");
Img.setAttribute("id", "ImgTr" +(i));
document.getElementById("galeria" +(i)).appendChild(Img);

/.../ /.../

var Img = document.createElement("tr");
Img.setAttribute("id", "ImgTr" +(i));
document.getElementById("galeria" +(i)).appendChild(Img);

var Imgz = document.createElement("td");
var image =document.createElement("img");
image.setAttribute("id", "imageID" +(i));
image.setAttribute("className", "bordered");
image.setAttribute("src","http://placehold.it/200/200/pink/black");
image.setAttribute("onclick","imgClick(this)");

image.src = window.URL.createObjectURL(fileList[i]);
  image.height = 50;
  image.with = 50;
  image.onload = function(){
    window.URL.revokeObjectURL(this.src);
  }

Now this is the function i want to call if the image is clicked on.现在这是我想在点击图像时调用的函数。 This function is supposed to show a border around the image clicked by the user.此功能应该在用户单击的图像周围显示边框。

 function imgClick(img) {

 if (img.className.indexOf('bordered') > -1) {
 img.className = img.className.replace('bordered', '').trim();
 } else {
 img.className += ' bordered';
 }

It compares the img clicked id atributte with the others images ids, and when it equals it shows the name of the file stored in the array NameFile它将 img 点击的 id 属性与其他图像 id 进行比较,当它相等时,它显示存储在数组 NameFile 中的文件的名称

 for( var i=0; i<NameFile.length;i++){
 if("imageID"+[i]===img.getAttribute("id")){ 
 alert(NameFile[i]);
 }
 }
 }

The problem mostly lies with this line:问题主要在于这一行:

var imgTag=document.getElementsByTagName('img');

as document.getElementsByTagName('img');作为document.getElementsByTagName('img'); returns a HTMLCollection and not a single element.返回一个 HTMLCollection 而不是单个元素。 So when you try setting the style prop, you are doing it on the HTMLCollection and not the actual node因此,当您尝试设置样式道具时,您是在 HTMLCollection 而不是实际节点上进行设置

Try this instead:试试这个:

 function imgClick(img){ img.style.border = '5px solid pink'; } var img = document.createElement('img'); img.setAttribute('src','http://placehold.it/200/200/pink/black'); img.setAttribute('onclick','imgClick(this)'); document.body.append(img);

EDIT:编辑:

If you want the second click to remove the border, there are several ways to do it.如果你想第二次点击去除边框,有几种方法可以做到。 One way would be to add a class to the element when it is clicked once.一种方法是在单击一次元素时向元素添加一个类。 We can then check for the class each time it is clicked to decide whether to add the border or remove it.然后我们可以在每次单击时检查该类,以决定是添加边框还是删除它。

Sample:样本:

 function imgClick(img) { if (img.className.indexOf('bordered') > -1) { // Already has border img.style.border = 'none'; img.className = img.className.replace('bordered', '').trim(); } else { // Does not have border img.style.border = '5px solid pink'; img.className += ' bordered'; } } var img = document.createElement('img'); img.setAttribute('src', 'http://placehold.it/200/200/pink/black'); img.setAttribute('onclick', 'imgClick(this)'); document.body.append(img);

Note: If the styling of the border does not change, you can move the styling out to a CSS style and just toggle the class on the image like this:注意:如果边框的样式没有改变,您可以将样式移出 CSS 样式,然后像这样切换图像上的类:

 function imgClick(img) { if (img.className.indexOf('bordered') > -1) { img.className = img.className.replace('bordered', '').trim(); } else { img.className += ' bordered'; } } var img = document.createElement('img'); img.setAttribute('src', 'http://placehold.it/200/200/pink/black'); img.setAttribute('onclick', 'imgClick(this)'); document.body.append(img);
 img.bordered{ border: 3px solid pink; }

EDIT 2:编辑2:

You can retrieve the file name as you set it and update your array您可以在设置时检索文件名并更新数组

 // Initialize empty array var myImages = []; function imgClick(img) { // Add image file name to array after getting it from data attribute myImages.push(img.dataset.name); console.log(myImages); } function appendImage() { var img = document.createElement('img'); var file = document.getElementById('file_in').files[0]; var url = window.URL.createObjectURL(file); img.setAttribute('src', url); img.setAttribute('onclick', 'imgClick(this)'); // Set the file name as a data attribute for later use img.dataset.name = file.name; document.body.append(img); }
 img.bordered { border: 3px solid pink; }
 <input type=file id="file_in" /> <button onclick="appendImage()">Upload</button>

onclick设置为属性不会在您已将 onclick 分配给图像的图像上设置事件

image.onclick = imgclick

Instead of adding an "onclick" attribute, I strongly advise you add an event listener to your img element.我强烈建议您为 img 元素添加一个事件侦听器,而不是添加“onclick”属性。

image.addEventListener("click", imgClick);

There is also an issue in your imgClick function : you don't need to look for your img element in there.您的imgClick函数中也存在一个问题:您无需在其中查找 img 元素。 You can instead add an event variable to your function declaration.您可以改为将事件变量添加到您的函数声明中。 That way you can retrieve the events target and do whatever you want with it :这样你就可以检索事件目标并用它做任何你想做的事情:

function imgClick(event) {
    event.target.style.border='2px solid #33cc33';
}

If you want to set onclick, then you need to set the property directly如果要设置onclick,那么就需要直接设置属性

image.onclick = imgClick;

Better solution would be to add event listener instead更好的解决方案是添加事件侦听器

image.addEventListener( "click", imgClick ); 

And you imgClick method becomes而你的imgClick方法就变成了

function imgClick(e){      
    var imgTag = e.currentTarget;
    imgTag.onload = function()
    {
        window.URL.revokeObjectURL( imgTag.src );
        imgTag.hasImageLoaded = true;
    }
    if ( imgTag.hasImageLoaded )
    {
        imgTag.style.border = '2px solid #33cc33';
    }
}

or或者

function imgClick(e){
    var imgTag = e.currentTarget;
    imgTag.addEventListener("load", function()
    {
        window.URL.revokeObjectURL( imgTag.src );
        imgTag.hasImageLoaded = true;
    });
    if ( imgTag.hasImageLoaded )
    {
        imgTag.style.border = '2px solid #33cc33';
    }
}

You can access to clicked item using event.target , like so:您可以使用event.target访问单击的项目,如下所示:

function imgClick(e) {  
  e.target.style.border = '2px solid #33cc33';  
}        

And bind event like below (as you did in your code):并绑定如下事件(就像您在代码中所做的那样):

image.onclick = imgClick;

Or using addEventListener :或者使用addEventListener

image.addEventListener("click", imgClick, false);

Notice that var imgTag = document.getElementsByTagName('img') returns array (like) of found item(s)/node(s), so imgTag.style... won't work.请注意, var imgTag = document.getElementsByTagName('img')返回找到的项目/节点的数组(类似),因此imgTag.style...将不起作用。

Also you can create the image with the HTMLInstance:您也可以使用 HTMLInstance 创建图像:

<div id="gallery"></div>

<script>
function createImg(src, height, weight, onclick) {
    const img = new Image(height, weight)
    img.src = src
    img.onclick = onclick
    return img
}

function addNewImage(image) {
    gallery.appendChild(image)
}

function handleClick () {
    alert('Image catch click event!')
}

const src = 'https://loremflickr.com/320/240'
const img1 = createImg(src, 100, 100, handleClick)

addNewImage(img1)
</script>

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

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