2014-12-03 116 views
0

我有一個可排序的元素網格,它在用戶移動元素後將其值更新爲數據庫。問題是,我不知道如何在不重新加載頁面的情況下將以前所有元素的ID更新爲新的元素。在PHP中,我會做這樣的事情(來自我的一箇舊頁面的FAQ的代碼),但是我不能使用PHP(它必須在沒有任何頁面重新加載的情況下發生,在用戶移動元素後立即發生) :

if ($old_order > $order){ 
    $result = dbquery("UPDATE faq SET orders=orders+1 WHERE orders>='$order' AND orders<='$old_order'"); 
}else{ 
    $result = dbquery("UPDATE faq SET orders=orders-1 WHERE orders>='$old_order' AND orders<='$order'"); 
} 

我想這樣做與jQuery,基本上我有ID 7個元素從0到6,每次用戶改變位置,我序列化和使用Ajax發送到一個PHP代碼,節省了它。

現在能做什麼:

  1. 移動elemtent 1至4位。
  2. 保存和作品。
  3. 移動元素3,從第4位2
  4. 移到元素1位回到他的老之一,因爲它 的ID仍然是1,而不是4

我想要做什麼:

  1. 移動元件1至第4位
  2. 元件1的變化ID從1至4
  3. 更改ID的元素2,3和4由-1到id 1,2和3

我希望有人能理解我並能幫助我。

jQuery代碼我actauly使用:

$(".content-page").sortable({ 
    start: function(e,ui){ 
     ui.placeholder.height($(".sorted-icons").outerHeight(true)); 
     ui.placeholder.width($(".sorted-icons").outerWidth(true)); 
    }, 
    placeholder: 'placeholder', 
    items: '.sorted-icons:not(.new_icon)', 
    update: function(e,ui) { 
     var order = $(this).sortable("serialize") + '&order=icons' + '&content_id=' + $(this).attr("data-shortcut-id"); 
     console.log(order); 
     $.post("page_ajax.php", order).done(function(data){ 
      console.log(data); 
     }).fail(function(data){ 
      console.log(data); 
     }); 
    } 
}).disableSelection(); 

HTML代碼基本上看起來是這個內容的div這就是內部irelevant:

echo "<div class='sorted-icons' id='icon_$id'>"; 

如果您有任何問題,只是評論和生病嘗試回答他們並更新任務。

固定的jQuery:

var i = 0; 
$(this).children('.sorted-icons').each(function(){ 
    $(this).attr('id', 'icon_' + i); 
    i++; 
}); 

仍然有PHP的一部分壽的問題。它將它們保存在奇怪的命令中。

+0

我不明白 - 你能夠在這裏使用PHP嗎? – DaemonOfTheWest 2014-12-03 05:39:52

+0

不,我不得不使用jQuery,因爲每次用戶移動某個元素時都無法重新加載頁面。 – MiChAeLoKGB 2014-12-03 06:01:25

+0

你可以爲此創建一個小提琴 – baao 2014-12-03 06:06:43

回答

0

好了,我在我的PHP代碼,一個小錯誤,但我設法解決了jQuery用的代碼非常簡單PICE:

$(".content-page").sortable({ 
    start: function(e,ui){ 
     ui.placeholder.height($(".sorted-icons").outerHeight(true)); 
     ui.placeholder.width($(".sorted-icons").outerWidth(true)); 
    }, 
    placeholder: 'placeholder', 
    items: '.sorted-icons:not(.new_icon)', 
    update: function(e,ui) { 
     var order = $(this).sortable("serialize") + '&order=icons' + '&content_id=' + $(this).attr("data-shortcut-id"); 
     console.log(order); 
     $.post("page_ajax.php", order); 
     // THIS PART // 
     var i = 0; 
     $(this).children('.sorted-icons').each(function(){ 
      $(this).attr('id', 'icon_' + i); 
      i++; 
     }); 
     // THIS PART // 
    } 
}).disableSelection(); 

希望可以幫助別人。