1 回答
TA贡献1876条经验 获得超5个赞
首先,您必须onclick="search()"从表格移动到每个表格img,这是因为您必须处理被单击的图像,而不是整个表格。您必须以某种方式将单击的图像与其他图像进行比较,对吧?
因此,我搜索了所有img标签,然后for loop添加了具有搜索功能的单击事件侦听器。
现在,当您单击图像时,您可以捕获该图像的 src。这将是与其他图像进行比较的关键,因为它对于每个图像来说都是唯一的值。
现在,当我们单击图像的 src 时,我们可以将其与其他图像进行比较。当它们相等时,我们可以为该图像添加边框。
一切都在下面的代码片段中进行了解释:)
//Find all images
let allImages = document.querySelectorAll('img');
//Paragraph where we will display how many times we have same image
let result = document.getElementById('count');
//Add event listener to every image
for(let i=0;i<allImages.length;i++){
allImages[i].addEventListener('click',search);
}
//Search function
function search(e){
//Get clicked img src
let clickedImgSrc = e.target.src;
//Get rid of things we don't need. We will use only directory/imagename.jpg for comparing
let clickedImgDirectory =clickedImgSrc.indexOf('my_files/');
let clickedImgName = clickedImgSrc.substr(clickedImgDirectory);
//Initialize counter
let count = 0;
//Loop thru all images, get src of looped image, get rid of things we don't need
for(let i=0;i<allImages.length;i++){
let imgSrc = allImages[i].src;
let imgDirectory = imgSrc.indexOf('my_files/');
let imgName = imgSrc.substr(imgDirectory);
//Compare looped img with clicked img, if they're equal increase count by 1 and add border to that image.
if(imgName === clickedImgName){
count++;
allImages[i].style.border = '5px solid red';
}else{
allImages[i].style.border = 'none';
}
}
//Write count value to paragraph
return result.innerText = 'This photo exists '+count+' times.';
}
<p id="count"></p>
<table style="width: 100%" id="myT">
<tbody>
<tr>
<td><img src="./my_files/k5.jpg"></td>
<td><img src="./my_files/k2.jpg"></td>
<td><img src="./my_files/k2.jpg"></td>
<td><img src="./my_files/k4.jpg"></td>
<td><img src="./my_files/k2.jpg"></td>
</tr>
<tr>
<td><img src="./my_files/k3.jpg"></td>
<td><img src="./my_files/k3.jpg"></td>
<td><img src="./my_files/k4.jpg"></td>
<td><img src="./my_files/k4.jpg"></td>
<td><img src="./my_files/k1.jpg"></td>
</tr>
<tr>
<td><img src="./my_files/k4.jpg"></td>
<td><img src="./my_files/k2.jpg"></td>
<td><img src="./my_files/k2.jpg"></td>
<td><img src="./my_files/k4.jpg"></td>
<td><img src="./my_files/k2.jpg"></td>
</tr>
<tr>
<td><img src="./my_files/k1.jpg"></td>
<td><img src="./my_files/k5.jpg"></td>
<td><img src="./my_files/k5.jpg"></td>
<td><img src="./my_files/k3.jpg"></td>
<td><img src="./my_files/k2.jpg"></td>
</tr>
<tr>
<td><img src="./my_files/k5.jpg"></td>
<td><img src="./my_files/k3.jpg"></td>
<td><img src="./my_files/k5.jpg"></td>
<td><img src="./my_files/k5.jpg"></td>
<td><img src="./my_files/k5.jpg"></td>
</tr>
</tbody>
</table>
添加回答
举报