2016-08-24 114 views
2

我一直在試圖弄清楚如何重新排列照片的順序。但他們必須符合正確的功能。我似乎無法弄清楚。如果你有三張照片是這樣的:HTML5重新排列元素

<img id='slot1' src="img1.jpg" onClick="function1();"> 
<img id='slot2' src="img2.jpg" onClick="function2();"> 
<img id='slot3' src="img3.jpg" onClick="function3();"> 

我可以重新排序的實際的形象,但我怎麼重新排序的圖像及其相關功能?

例如,點擊img1.jpg時,應始終運行功能1(),不管他們是什麼樣的順序感謝

編輯:最初,我沒有正確發佈的代碼。

+0

你可以分享代碼顯示你到目前爲止嘗試過嗎? – apokryfos

+1

需要使用代碼標籤來包圍你的代碼元素 –

+0

你的意思是你試圖用javascript動態重新排列圖片嗎?搜索'parentElement'和'insertBefore' –

回答

1

這裏我們看到另一個不使用強大的內聯事件處理程序的原因。更改HTML到

<div class="image-container"> 
    <img id='slot1' src="img1.jpg" /> 
    <img id='slot2' src="img2.jpg" /> 
    <img id='slot3' src="img3.jpg" /> 
</div> 

,並附事件是這樣的:

var container = document.querySelector('.image-container') 
container.addEventListener('click', function(e) { 
    if (e.target.tagName === 'IMG') { 
    // find the index of e.target 
    // call function1,2 or 3 depending on index 
    } 
}) 

如何找到索引:檢查這answer

這是一個快速演示:https://jsfiddle.net/th174cnz/

0

確實有比這更優雅的方法,但是如果您只是簡單地交換圖像源,則可以使用onclick事件完全相同。

var temp=document.getElementById('slot1').onclick; 
document.getElementById('slot1').onclick=document.getElementById('slot2').onclick; 
document.getElementById('slot2').onclick=temp; 
0

假設你已經改變了圖像的src動態,這是一個簡單的代碼

HTML

<img id="slot1" src="http://chandra.harvard.edu/graphics/photo/high_res_thm.jpg" onclick="function1()"> 
<img id="slot2" src="http://umbra.nascom.nasa.gov/images/latest_mk4_icon.gif" onclick="function2()"> 
<input type="button" id="button" onclick="shuffleImages()" value="Click"/> 

的Javascript

function shuffleImages() 
{ 
    var src1 = document.getElementById("slot1").getAttribute('src'); 
    var src2 = document.getElementById("slot2").getAttribute('src'); 
    var click1 = document.getElementById("slot1").getAttribute('onclick'); 
    var click2 = document.getElementById("slot2").getAttribute('onclick'); 
    document.getElementById("slot1").setAttribute("src", src2); 
    document.getElementById("slot1").setAttribute("onclick", click2); 
    document.getElementById("slot2").setAttribute("src", src1); 
    document.getElementById("slot2").setAttribute("onclick", click1); 
} 

這裏是簡單的演示: - https://jsfiddle.net/900d62dL/ 注意:上面提供的解決方案是優秀的和優化的。這個演示只是爲了您的理解。