Am besten wäre es, sie in eine wiederverwendbare benutzerdefinierte Funktion zu verpacken:
$.fn.swap = function(other) {
$(this).replaceWith($(other).after($(this).clone(true)));
};
Damit Sie es als verwenden können:
one.swap(other);
Le site clone(true)
wird verwendet, damit auch Ereignisse berücksichtigt werden.
Hier ist ein SSCCE die den Austausch von Zeilen mit der nächsten Zeile (falls vorhanden) demonstriert:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2078626 part I</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$.fn.swap = function(other) {
$(this).replaceWith($(other).after($(this).clone(true)));
};
$(document).ready(function() {
$('tr').css('cursor', 'pointer').click(function() {
$(this).swap($(this).next());
});
});
</script>
</head>
<body>
<table>
<tbody>
<tr><td>row1col1</td><td>row1col2</td><td>row1col3</td></tr>
<tr><td>row2col1</td><td>row2col2</td><td>row2col3</td></tr>
<tr><td>row3col1</td><td>row3col2</td><td>row3col3</td></tr>
<tr><td>row4col1</td><td>row4col2</td><td>row4col3</td></tr>
<tr><td>row5col1</td><td>row5col2</td><td>row5col3</td></tr>
</tbody>
</table>
</body>
</html>
Hier ist ein SSCCE, das zeigt, wie es in Ihrem speziellen Fall verwendet werden kann:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2078626 part II</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$.fn.swap = function(other) {
$(this).replaceWith($(other).after($(this).clone(true)));
};
$(document).ready(function() {
$('button.swap').click(function() {
$('#table tr:eq(1)').swap($('#table tr:eq(3)'));
});
});
</script>
</head>
<body>
<table id="table">
<tbody>
<tr><td>row1col1</td><td>row1col2</td><td>row1col3</td></tr>
<tr><td>row2col1</td><td>row2col2</td><td>row2col3</td></tr>
<tr><td>row3col1</td><td>row3col2</td><td>row3col3</td></tr>
<tr><td>row4col1</td><td>row4col2</td><td>row4col3</td></tr>
<tr><td>row5col1</td><td>row5col2</td><td>row5col3</td></tr>
</tbody>
</table>
<button class="swap">swap rows 2 and 4</button>
</body>
</html>
Beachten Sie, dass der Elementindex auf Null basiert, daher ist die 1
y 3
en :eq()
.