2016-08-24 112 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/ 注意:上面提供的解决方案是优秀的和优化的。这个演示只是为了您的理解。