Помогите чайнику
В двух словах о самой проблеме:
Вобщем надо сделать возможность без перезагрузки страницы перещать строки в таблице <table> <tr><td id="td1">строка 1</td><td><asp:Image ID="Image1" runat="server" ImageUrl="~/down_f.gif" Height="16px" Width="16px"/></td></tr> <tr><td id="td2">строка 2</td><td><asp:Image ID="Image2" runat="server" ImageUrl="~/down_f.gif" Height="16px" Width="16px"/></td><td> <asp:Image ID="Image3" runat="server" ImageUrl="~/up_f.gif" Height="16px" Width="16px"/></td></tr> <tr><td id="td3">строка 3</td><td><asp:Image ID="Image4" runat="server" ImageUrl="~/up_f.gif" Height="16px" Width="16px"/></td></tr> </table>Пробовал сделать так:
$("#td1").replaceWith($("#td2"));
он их перемещает, но при этом затирает td1. Помогите, как мне правильно сделать. Заранее всем спасибо. |
конечно затирает, написано же - replace - заменить. Только не путаете ли вы понятия строки и ячейки?
Вкратце именно для решения того что попытались сделать вы:
var $tr1 = $('#td1').parent();
var $tr2 = $('#td2').parent();
$tr1.prepend($('#td2'));
$tr2.prepend($('#td1'));
p.s. и в будущем, постарайтесь давать вменяемые названия своим темам. |
спасибо огромнейшее. только у меня теперь еще вопрос появился. я почитал про .prepend(content) и понял, что он добавляет содержимое #td2 в #tr1. по идее должно за тогда отображаться так
строка 2строка 1 а она отображает правильно) в чем фокус?) Цитата:
|
Цитата:
Кстати, в IE ваш код работать не будет, с таблицами там работать можно только специальными функциями insertCell, insertRow, … и т.д. А в .prepend() эта особенность не учтена. |
exec, Вроде бы все работает, если я не ошибаюсь.
Jesus, как вариант что-то вроде этого:
jQuery.fn.tablesort = function(options) {
switch (options) {
case 'remove': return this.each(function(){
jQuery('tbody > tr', this).add(this).unbind('.tablesort');
}).removeClass('tablesort');
default: return this.each(function() {
options = jQuery.extend({}, options);
// The first order of business is to bind a function to the mousedown event
jQuery(this).addClass('tablesort').find('tbody > tr').unbind('.tablesort').bind('mousedown.tablesort', function(e) {
// store jQuery(this) tr element in a variable to allow faster access in the functions soon to be declared
var self = this,
tr = jQuery(self),
rows = jQuery('tr', tr.parent()),
start = rows.index(self);
// Add to TR element drag-marking class
tr.one('mousemove.tablesort', function(){
tr.addClass('tablesort-drag');
});
// jQuery has a fantastic function called mouseenter() which fires when the mouse enters
// This code fires a function each time the mouse enters over any TR inside the tbody -- except jQuery(this) one
rows.not(self).bind('mouseenter.tablesort', function(e) {
if ( this.rowIndex === self.rowIndex ) return;
// Check position of old tr to see whether to pop this before or after
// If jQuery(this) index greater than tr index, we are moving DOWN the page and
// insert tr after jQuery(this), where jQuery(this) is the tr that is being hovered over.
// If jQuery(this) index lower than tr index, we are moving UP the page and insert tr before jQuery(this).
if ( this.rowIndex > self.rowIndex ) {
jQuery(this).after(self);
} else {
jQuery(this).before(self);
}
});
// Clear garbage, 'cause we have closures
rows = null;
// Now, bind a function that runs on the very next mouseup event that occurs on the page
// This checks for a mouse up *anywhere*, not just on table rows so that the function runs even
// if the mouse is dragged outside of the table.
jQuery('body').one('mouseup.tablesort', function() {
// Remove from TR element drag-marking class and one-time-run bind, if needed
tr.unbind('mousemove.tablesort');
// Remove the mouseenter & mousemove events from the tbody so that the TR element stops being moved
var rows = jQuery('tr', tr.parent()).removeClass('tablesort-drag').unbind('mouseenter.tablesort'),
end = rows.index(self);
if (start !== end && options.change) {
var thread = rows.get().slice(Math.min(start, end), 1 + Math.max(start, end));
if (start > end) thread.reverse();
options.change(thread);
}
// Make text selectable for IE again with
// The workaround for IE based browsers
if (jQuery.browser.msie) {
jQuery(document).unbind('selectstart.tablesort');
}
});
// This part if important. Preventing the default action and returning false will
// Stop any text in the table from being highlighted (this can cause problems when dragging elements)
e.preventDefault();
// The workaround for IE based browers
if (jQuery.browser.msie) {
jQuery(document).bind('selectstart.tablesort', function() {
return false;
});
}
//return false;
});
});
}
};
|
Спасибо всем большое. Есть еще вопрос) Вот в данном примере
var $tr1 = $('#td1').parent();
var $tr2 = $('#td2').parent();
$tr1.prepend($('#td2'));
$tr2.prepend($('#td1'));
перемещаются сами ячейки или их контент? просто, если сами ячейки, то мне надо как-то сделать перемещение именно их контента. |
Jesus, перемещаются строки таблицы (TR). Только тут нужен не prepend, а .html():
var $td1 = $('#td1').html();
$('#td1').html($('#td2').html());
$('#td2').html($td1);
|
html туфта -- все обработчики со внутренностей пропадут.
|
Спасибо большое! Сработало.
|
| Часовой пояс GMT +3, время: 16:40. |