如何通过JavaScript访问img元素的title属性?

时间:2017-04-13 20:22:56

标签: javascript html image

有一个空div,将插入一个图像元素。

<div id="divOne" class="div"></div> 
<!-- blank div this is the html div, and is blank so as to append img using js code below. -->

然后我使用JavaSctipt将图像添加到DOM。

var createImage = function(src, title) {
 var img = new Image();
 img.src = src;
 img.title = title;
 return img;
};

var imgArray = [];
imgArray.push(createImage('Assets/banana.png', 'banana'));

divOne.append(imgArray[0]);

如何访问图像的tittle属性?例如

divOne.onclick = function divOneClicked() {

 console.log('div 1 clicked');

 if ( ???.title == winImg.title) {
 console.log('banana/lose');
 }
}

我如何将div img的标题与另一个img的标题进行比较?

3 个答案:

答案 0 :(得分:0)

您正在将它们加载到数组中,请查看此选项:

var createImage = function(src, title) {
 var img = new Image();
 img.src = src;
 img.title = title;
 return img;
};

var imgArray = [];
imgArray.push(createImage('Assets/banana.png', 'banana'));
imgArray.push(createImage('Assets/orange.png', 'orange'));
imgArray.push(createImage('Assets/grapefruit.png', 'grapefruit'));

// Here I access a property of one of the elements...
 console.log(imgArray[0].title);

相反,如果您正在寻找DOM本身中图像元素的标题,请尝试:

var createImage = function(src, title) {
  var img = new Image();
  img.src = src;
  img.title = title;
  return img;
};

var imgArray = [];
imgArray.push(createImage('Assets/banana.png', 'banana'));
imgArray.push(createImage('Assets/orange.png', 'orange'));
imgArray.push(createImage('Assets/grapefruit.png', 'grapefruit'));

for (var i = 0, j = imgArray.length; i < j; i++) {
  var el = document.createElement("div");
  document.body.appendChild(el);
  el.appendChild(imgArray[i]);
  el.addEventListener("click", function() {
    var myImage = this.querySelector("img");
    console.log(myImage.title);
  });
}

编辑这个迭代imgArray并为每个图像创建div。每个div都会通过处理自己的点击来显示自己的子图像标题。

答案 1 :(得分:0)

您可以使用:

imgArray [i] .title for any index i

答案 2 :(得分:0)

您也可以使用Group 1 item1 item2 item3 Group 2 item1 item2 ...

$('img', "#divOne").attr('title');
var createImage = function(src, title) {
 var img = new Image();
 img.src = src;
 img.title = title;
 return img;
};

var imgArray = [];
imgArray.push(createImage('Assets/banana.png', 'banana'));
divOne.append(imgArray[0]);
var a = $('img', "#divOne").attr('title');
console.log(a);