插入一个接一个的div

时间:2016-08-04 19:19:07

标签: javascript jquery html

我试图移动'从一个位置到另一个位置的div。我使用.after,但它没有调用该方法?我做错了什么?



var row = $('<div class="row">Another row inserted</div>');
$('.container').append(row);

$('.button').click(function() {
	$('.row').addClass('row-changed');
	$('.container:eq(2)').after(row);
});
&#13;
.row {
  color: blue;
}
.row-changed {
  color: red;
}
&#13;
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<div class='container'>
  <button class='button'>Move</button>
  <div class='row'>Row here</div>
  <div class='row'>Row here</div>
  <div class='row'>Row here</div>
  <div class='row'>Row here</div>
  <div class='row'>Row here</div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

如果您尝试选择.container的第n个孩子,.container:eq(2)将无效,因为它正在尝试选择第二个.container,而不是.container的第二个孩子{1}}。您可以改用:nth-child()选择器。

<强>的jQuery

$('.button').click(function() {
    $('.row').addClass('row-changed');
    $('.container > div:nth-child(2)').after(row);
});

var row = $('<div class="row">Another row inserted</div>');
$('.container').append(row);

$('.button').click(function() {
	$('.row').addClass('row-changed');
	$('.container > div:nth-child(2)').after(row);
});
.row {
  color: blue;
}
.row-changed {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
  <button class='button'>Move</button>
  <div class='row'>Row here</div>
  <div class='row'>Row here</div>
  <div class='row'>Row here</div>
  <div class='row'>Row here</div>
  <div class='row'>Row here</div>
</div>

<强> JSFiddle