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;
答案 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 强>