我有这个HTML:
<div class="content vertical-gradient">
<div id="button_id0" class="button services rounded-corners trans-effect"><a class="title-text" href="index.php?services">Tjänster</a></div>
<div id="button_id1" class="button prices rounded-corners trans-effect"><a class="title-text" href="index.php?prices">Priser</a></div>
<div id="button_id2" class="button about-me rounded-corners trans-effect"><a class="title-text" href="index.php?aboutme">Om mig</a></div>
</div>
当加载dom时,我从每个按钮保存文本(html),如下所示:
$(".button").each(function(index) {
//Store all texts (html) from buttons for later user with drag/drop
lastHtml[index] = $(this).html();
}
其中lastHtml
被定义为全局数组。
在某些情况下,我想更改按钮的html,但是当我将其拖放到某个地方时,我想回到原来的状态。因此,当dom加载到变量lastHtml-array时,我保存文本(html)。
在drop-section中我通过它的ID检索按钮的索引(索引号由元素按钮(useButtonId')检索,例如,button_id1将返回索引1,button_id2将在删除时返回index2。)
$( ".content").droppable({
accept: ".button.dragme", //Must come from this dragged element
drop: function( event, ui ) {
//Show ordinary text for button
var id = $(ui.helper).prop("id");
var idArray = id.split("_id"); //array of split between _id, example: [0] = button, [1] = 2
var useButtonId = idArray[1];
$(ui.helper).addClass("trans-effect").removeClass("dragme").removeClass("ui-draggable").html(lastHtml[useButtonId]);
}
}
但我真正想要的是这样的东西:(我希望有多少个我喜欢的按钮,而不必考虑id,但我仍然希望所有的html值都是加载dom时保存并在拖放特定按钮时恢复到原始状态。
<div class="content vertical-gradient">
<div name="button[]" class="button services rounded-corners trans-effect"><a class="title-text" href="index.php?services">Tjänster</a></div>
<div name="button[]" class="button prices rounded-corners trans-effect"><a class="title-text" href="index.php?prices">Priser</a></div>
<div name="button[]" class="button about-me rounded-corners trans-effect"><a class="title-text" href="index.php?aboutme">Om mig</a></div>
</div>
我想!?我可以使用index()
,但我真的无法弄清楚如何。我试过了:
$(ui.helper).index())
$('.content').index(ui.helper))
但它们似乎都没有返回正确的索引。
答案 0 :(得分:1)
使用.data()
var $btns=$('.button')
$btns.each(function(){
var $btn=$(this);
$btn.data('lastHtml', $btn.html());
});
data()
既是getter又是setter,所以要重置:
$(this).html( $(this).data('lasthtml') );
或者创建一个属性或数据存储,如btn-index
,以引用存储的数组
$btns.each(function(index) {
//Store all texts (html) from buttons for later user with drag/drop
lastHtml[index] = $(this).html();
$(this).attr('btn-index',index)/* or*/.data('btn-index',index);
});
如果仅在您的可放置示例中使用它,那么在元素上存储似乎是最简单的方法