我想切換兩個div的位置與onclick事件
如果你想交換兩個相鄰節點,你可以做簡單的東西作爲:
function swapAdjacent(el0, el1) {
el0.parentNode.insertBefore(el1, el0);
}
如果你想交換t中的任何兩個元素他DOM,你可以這樣做:
// Swap the postion in the DOM of el0 and el1
function swapElements(el0, el1) {
// Create a temp node that can replace el0
var tmp = el0.cloneNode(false);
// Replace el0 with tmp
el0.parentNode.replaceChild(tmp, el0);
// Replace el1 with el0
el1.parentNode.replaceChild(el0, el1);
// Replace temp node with el1
tmp.parentNode.replaceChild(el1, tmp);
}
和一些測試標記:
<div id="d0">div 0</div>
<div id="d1">div 1</div>
<button onclick="
swapElements(document.getElementById('d0'), document.getElementById('d1'));
">Swap d0, d1</button>
<button onclick="
swapAdjacent(document.getElementById('d0'), document.getElementById('d1'));
">Swap adjacent</button>
過程中的兩個元素交換必須與周圍的元素,例如一致你不能用一個div來交換一個選項元素,並期望一切正常,但你可以用一個div來交換一個span。
如果你想通過點擊一個或另一個交換元素:
<div id="d0" onclick="swapElements(this, document.getElementById('d1'))">div 0</div>
<div id="d1" onclick="swapElements(this, document.getElementById('d0'))">div 1</div>
所以應該發生什麼?你知道'emptyDivClass'沒有樣式,它是點擊應用的類,添加樣式會有所作爲 - > ** http://jsfiddle.net/r84BZ/1/**? – adeneo
我在你的完整代碼中看到你正在爲多個元素分配id「filled」和「empty」。這是不好的做法。 Id屬性應始終是唯一的。您應該改用類。 – Johnsonium
我們是否可以添加一些建議以使其超出問題範圍? – cgatian