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>
添加回答
舉報