2015-04-29 101 views
-1

我有一個changeImage函數,我想在有人單擊圖像時執行該函數。問題是我有100個可以觸發該功能的圖像。用於多個onclick事件的相同javascript函數

我想到的唯一解決方案是製作數百個不同的id和數百種不同的功能,但是作爲解決方案,我只能點擊一個圖像,並且每次我想點擊另一個圖像時都需要刷新頁面。

這裏是我的代碼: -html

<img id="image" onclick="changeImage()" src="images/pic1.png"> 

-js

  <script> 
     function changeImage() { 
      var image = document.getElementById('image'); 
      if (image.src.match("pic1")) { 
       image.src = "images/pic2.png"; 
      } else{ 
       image.src = "images/pic1.png"; 
      } 
     } 
     </script> 
+0

是否有隻有2個圖像?圖片1和2?所以每次點擊這100張圖片時,它只會在圖片1和2之間翻轉? – Huangism

回答

0

您可以使用此:

HTML代碼:

<img id="image" onclick="changeImage(this)" src="images/pic1.png"> 

和JavaScript合作因爲這個:

function changeImage(img) { 
    if (img.src.match("pic1")) { 
     img.src = "images/pic2.png"; 
    } else { 
     img.src = "images/pic1.png"; 
    } 
} 

這應該適合你!

0

試試這個:

<img class="image" src="images/pic1.png"> 

    $('.image').on('click', function() { 
     if ($(this).attr("src").match("pic1")) { 
      $(this).attr("src") = "images/pic2.png"; 
     } else{ 
      $(this).attr("src") = "images/pic1.png"; 
     } 
    }); 
+0

我喜歡這裏的CSS選擇器方法,但請記住,上面的代碼需要jQuery。 – BluDragn

+0

OP的問題有一個jQuery標籤。 – taxicala

0

一個更好的方法是使用不顯眼的JavaScript和addEventListener方法。

除了在您的html中添加onclick屬性,您可以添加通用class,如clickable-image。然後在Javascript中,找到與此class所有元素,並告訴他們聽click事件。

當點擊發生時,它將執行changeImage並傳入MouseEvent作爲參數。該事件有一個名爲target的屬性,它告訴你哪個元素被完全點擊。

// This is the method that will be called when a click occurs 
 
function changeImage(event) { 
 
    // Get the target of the event (the image that was clicked) 
 
    var image = event.target; 
 
    if (image.src.match("ff0000")) { 
 
    image.src = "http://placehold.it/100/0000ff"; 
 
    } else { 
 
    image.src = "http://placehold.it/100/ff0000"; 
 
    } 
 
} 
 

 
// Find all clickable images that exist in the DOM 
 
var images = document.getElementsByClassName('clickable-image'); 
 
for (var i = 0; i < images.length; i++) { 
 
    // For each clickable image, listen to the 'click' mouseevent 
 
    images[i].addEventListener('click', changeImage); 
 
}
<img class="clickable-image" src="http://placehold.it/100/ff0000"> 
 
<img class="clickable-image" src="http://placehold.it/100/0000ff">

點擊 「運行代碼片斷」 上面看到它在行動

+0

非常感謝!這對我有用。 –

相關問題