gpt4 book ai didi

javascript - jQuery 附加和前置 div 和点击事件

转载 作者:搜寻专家 更新时间:2023-10-31 22:49:53 25 4
gpt4 key购买 nike

我想通过单击将 div 从一个父 div 转移到另一个父 div。

请查看下面的 jsfiddle 页面以供引用

http://jsfiddle.net/fb7Tq/97/

我想在任何一侧转移 div 当我点击任何灰色的 div 它迁移到其他 div 框并将样式更改为红色当我单击返回红色 div 它应该回到原来的灰色样式.

我怎样才能做到这一点?

HTML:

<div class="section1">
<div id="1" >1</div>
<div id="2" >2</div>
<div id="3" >3</div>
<div id="4" >4</div>
<div id="5" >5</div>
<div id="6" >6</div>
<div id="7" >7</div>
<div id="8" >8</div>
</div>

<div class="section2"></div>

CSS:

.section1 div{height:25px; background-color:#333; color:#FFF; border:1px solid red; margin-bottom:2px; width:50px;}

.section2 div{height:25px; background-color:red; color:yellow; border:1px solid green; margin-bottom:2px; width:150px;}

.section1{float:left; margin-right:50px;}
.section2{float:left}

还有我的 JavaScript:

$(document).ready(function() {
function testclick() {
var iLoc = $(this).attr("id");
$('.section2').append(this);
$('#'+iLoc).unbind('click', testclick);
}

function testclick2() {
alert("s");
var iLoc = $(this).attr("id");
$('.section1').append(this);
this.unbind('click', testclick2);
}
$('.section1 div').bind('click', testclick);
$('.section2 div').bind('click', testclick2);


});

最佳答案

改变:

$('.section1 div').bind('click', testclick);
$('.section2 div').bind('click', testclick2);

进入

$('.section1 div').live('click', testclick);
$('.section2 div').live('click', testclick2);

您现在可以从函数中删除 .unbind()

保持位置:

$(document).ready(function() {
$('.section1 div').each(function(){
$(this).data("pos", $(this).index());
});

function testclick() {
var node = $(this);
var success = false;
$('.section2 div').each(function(){
if($(this).data("pos") > node.data("pos"))
{
$(this).before(node);
success = true;
return false; // Jump out of loop
}
});

if(!success)
{
$('.section2').append(node);
}
}

function testclick2() {
var node = $(this);
var success = false;
$('.section1 div').each(function(){
if($(this).data("pos") > node.data("pos"))
{
$(this).before(node);
success = true;
return false; // Jump out of loop
}
});

if(!success)
{
$('.section1').append(node);
}
}
$('.section1 div').live('click', testclick);
$('.section2 div').live('click', testclick2);


});

持仓演示:http://jsfiddle.net/fb7Tq/109/

关于javascript - jQuery 附加和前置 div 和点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8180415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com