单击jQuery后移动div()父项

时间:2013-09-08 08:09:49

标签: javascript jquery html jquery-after

在下面的代码中,当我点击<div class="move">I was moved to the parent.</div>时,如何在我单击的元素的父元素之后移动Add New

我把一切都做对了,但我不能做我需要移动它的部分after()

你能帮忙吗?

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Side bar poll thingy</title>
<script type="text/javascript" src="http://localhost/site/scripts/jQueryCore.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('.add').click(function() {
    $("#container").find('.flag, .edit, .delete').remove();
    $(this).parent("div").after(".move");

    });
});
</script>
</head>
<body>
<div id="container">
    <div class="h1" data-id="1">Teachers <span class="add" data-id="US01">Add New</span></div>
    <div class="h2" data-id="2">Who is your favorite Math teacher? <span class="add" data-id="US02">Add New</span></div>
        <br>
    <div class="h1" data-id="8">Restaurants <span class="add" data-id="US10">Add New</span></div>
    <div class="h2" data-id="9">Which is your favourtie restaurant in town? <span class="add" data-id="US20">Add New</span></div>

    <div class="move">I was moved to the parent.</div>
</div>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

.after()不接受选择器,目前您在所选元素后面插入.move字符串。您可以改为使用.insertAfter()方法:

$(".move").insertAfter(this.parentNode);

http://jsfiddle.net/RYzpG/

答案 1 :(得分:1)

尝试这个小提琴http://jsfiddle.net/QP3MZ/

$(document).ready(function () {
    $('.add').click(function () {
        $("#container").find('.flag, .edit, .delete').remove();
        var $move = $('#container .move');
        $(this).parent("div").after($move);
    });
});

答案 2 :(得分:1)

此代码应该有效。

$(document).ready(function() {
    $('.add').click(function(e) {
        e.preventDefault();
        $("#container").find('.flag, .edit, .delete').remove();
        $('.move').insertAfter($(this).parent());
        //Or (Note we have to pass a jQuery element inside after, if we pass string then it will copy the string instead)
        //$(this).parent('div').after($('.move'));
    });
});

这里还有一个jsfiddle。您的工作原因是您在.after内传递一个字符串,jQuery会将其视为HTML字符串。你必须传递一个jQuery元素或DOM元素。见here