jquery replace issues
-
02-06-2021 - |
Question
I have series of divs, that represent similar to a chess board. but this is a kinda tricky chess. basically users clicks on a piece, and clicks on enemy piece. if it can kill. it should move it to the enemies position. And enemy should be deleted.
<div class="column" data-square="4-4">
<div class="white-king lol">a</div>
</div>
<div class="column" data-square="4-5">
<div class="black-pawn lol">b</div>
</div>
<div class="column" data-square="4-6">
<div class="blue lol">c</div>
</div>
//so when users first clicks on whiteking, we get the data-square, assign it to a variable $from, then clicks on enemy black-pawn. does some validation in server, and should move the
inner div of square = 4-4 to inner div of square = 4-5 , the inner div of square = 4-5 should be deleted and the inner div of square= 4-4 should be presnet
I have tried using jquery clone. but it doesnt works out well fiddle: http://jsfiddle.net/jm4eb/13/
Solution
I personally wouldn't get too bent out of shape replacing one element with another. I'd look at just swapping the attributes from one element to another. Remove the white-king
class from one element and add it to another.
OTHER TIPS
This is not the good way still, but you can try
(function() {
var from = null;
var $change =null;
var to = null;
$(".column" ).click(function(){
if(from === null)
{
$(this).css("background-color","yellow");
from = $(this).data('square');
$change= ($('<div/>').append($(this).clone(true).children()).html());
}
else
{
to = $(this).data('square');
$(this).html("").html($change);
$('div[data-square="'+from+'"]').html("<div class=lol>empty</div>").css("background-color","");
from = to = null;
}
});
}());