Javascript 单击()后元素的更改顺序
我不想改变段落的顺序(用户点击的段落应该在顶部)。我想到了这个:Javascript 单击()后元素的更改顺序,javascript,jquery,Javascript,Jquery,我不想改变段落的顺序(用户点击的段落应该在顶部)。我想到了这个: <div> <p>11111111</p> <p>22222222</p> <p>33333333</p> </div> $("p").click(function(){ var a = $(this).index(); if (a != 0) { $(this).clone().prependTo("div");
<div>
<p>11111111</p>
<p>22222222</p>
<p>33333333</p>
</div>
$("p").click(function(){
var a = $(this).index();
if (a != 0) {
$(this).clone().prependTo("div");
$(this).remove();
}
})
11111111
2222222
33333333
$(“p”)。单击(函数(){
var a=$(this.index();
如果(a!=0){
$(this.clone().prependTo(“div”);
$(this.remove();
}
})
但它只“一次”起作用
距离不远,实际上要简单得多:只需在元素的父元素前面加上:
$(“p”)。单击(函数(){
var$this=$(this);
$this.prependTo($this.parent());
});代码>
11111111
2222222
33333333
距离不远,实际上要简单得多:只需在元素的父元素前面加上:
$(“p”)。单击(函数(){
var$this=$(this);
$this.prependTo($this.parent());
});代码>
11111111
2222222
33333333
您可以使用.insertBefore()代码>并且您也需要
$(“div”)。在('click','p:not(:n个子(1)),函数()上{
$(this).insertBefore('p:nth child(1)');
})
11111111
2222222
33333333
您可以使用.insertBefore()代码>并且您也需要
$(“div”)。在('click','p:not(:n个子(1)),函数()上{
$(this).insertBefore('p:nth child(1)');
})
11111111
2222222
33333333
或者更简单的$(this).parent().prepend(this)
@charlietfl:不确定这是否更简单,但确定。少了一行。:-)或者更简单的$(this).parent().prepend(this)
@charlietfl:不确定这是否更简单,但确定。少了一行。:-)