我有HTML代码:
<ul>
<li>Item 1: <button id="down_1">Down</button></li>
<li>Item 2: <button id="down_2">Down</button><button id="up_2">Up</button></li>
<li>Item 3: <button id="down_3">Down</button><button id="up_3">Up</button></li>
<li>Item 4: <button id="down_4">Down</button><button id="up_4">Up</button></li>
<li>Item 5: <button id="up_5">Up</button></li>
</ul>
并希望使用jQuery来更新列表顺序。
<script>
$(document).ready(function() {
$('[id^="down_"]').each(function() {
var id = this.id;
$('#' + id).click(function() {
///A code to change this <li>..</li> with the next one??
});
});
$('[id^="up_"]').each(function() {
var id = this.id;
$('#' + id).click(function() {
///A code to change this <li>..</li> with the previous one??
});
});
});
</script>
如何编写用于更改订单的JavaScript / jQuery代码?例如,如果我按下id =“down_3”的按钮,则结果为:
<ul>
<li>Item 1: <button id="down_1">Down</button></li>
<li>Item 2: <button id="down_2">Down</button><button id="up_2">Up</button></li>
<li>Item 4: <button id="down_4">Down</button><button id="up_4">Up</button></li>
<li>Item 3: <button id="down_3">Down</button><button id="up_3">Up</button></li>
<li>Item 5: <button id="up_5">Up</button></li>
</ul>
答案 0 :(得分:3)
疯狂猜测?
$(document).ready(function() {
$('[id^="up_"]').on('click', function() {
var li = $(this).closest('li');
li.prev('li').before(li);
});
$('[id^="down_"]').on('click', function() {
var li = $(this).closest('li');
li.next('li').after(li);
});
});
答案 1 :(得分:1)
相反,您可以使用.on()
$('[id^="down_"]').on('click',function() { });
并进行分类。
<script type="text/javascript">
$(function(){
$('[id^="down_"],[id^="up_"]').on('click',function(){
var row = $(this).parents("li:first");
if ($(this).is(".up"))
{
row.insertBefore(row.prev());
}
else
{
row.insertAfter(row.next());
}
});
});
</script>
Demo
强> 答案 2 :(得分:0)
@adeneo's answer的一种略微替代方法:
$('li button.down, li button.up').click(
function (e) {
e.preventDefault();
var that = $(this),
li = that.closest('li'),
direction = that.hasClass('down');
li[direction ? 'insertAfter' : 'insertBefore'](direction ? li.next() : li.prev());
});
请注意,我已将id
更改为共享的类名,以便于选择。