Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   Помогите чайнику (https://javascript.ru/forum/jquery/12059-pomogite-chajjniku.html)

Jesus 28.09.2010 22:23

Помогите чайнику
 
В двух словах о самой проблеме:
Вобщем надо сделать возможность без перезагрузки страницы перещать строки в таблице
<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.
Помогите, как мне правильно сделать. Заранее всем спасибо.

micscr 29.09.2010 08:34

конечно затирает, написано же - replace - заменить. Только не путаете ли вы понятия строки и ячейки?
Вкратце именно для решения того что попытались сделать вы:
var $tr1 = $('#td1').parent();
  var $tr2 = $('#td2').parent();
  $tr1.prepend($('#td2'));
  $tr2.prepend($('#td1'));


p.s. и в будущем, постарайтесь давать вменяемые названия своим темам.

Jesus 29.09.2010 17:44

спасибо огромнейшее. только у меня теперь еще вопрос появился. я почитал про .prepend(content) и понял, что он добавляет содержимое #td2 в #tr1. по идее должно за тогда отображаться так
строка 2строка 1
а она отображает правильно) в чем фокус?)

Цитата:

Только не путаете ли вы понятия строки и ячейки?
я имел ввиду строки (текст) внутри ячеек (строка 1, строка 2, ...)

exec 29.09.2010 17:52

Цитата:

а она отображает правильно) в чем фокус?)
Нет, всё-таки вы путаете строки и ячейки.

Кстати, в IE ваш код работать не будет, с таблицами там работать можно только специальными функциями insertCell, insertRow, … и т.д. А в .prepend() эта особенность не учтена.

e1f 29.09.2010 18:30

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;
            });
    
        });
    }
};

Jesus 30.09.2010 12:22

Спасибо всем большое. Есть еще вопрос) Вот в данном примере
var $tr1 = $('#td1').parent();  
var $tr2 = $('#td2').parent();  
$tr1.prepend($('#td2'));  
$tr2.prepend($('#td1'));

перемещаются сами ячейки или их контент?
просто, если сами ячейки, то мне надо как-то сделать перемещение именно их контента.

exec 30.09.2010 13:06

Jesus, перемещаются строки таблицы (TR). Только тут нужен не prepend, а .html():

var $td1 = $('#td1').html();
$('#td1').html($('#td2').html());
$('#td2').html($td1);

e1f 01.10.2010 20:08

html туфта -- все обработчики со внутренностей пропадут.

Jesus 06.10.2010 21:06

Спасибо большое! Сработало.


Часовой пояс GMT +3, время: 10:30.