本文介绍了jQuery UI 可排序:确定项目的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里是 JavaScript 的一个有趣用法:通过拖放重新排序项目.我页面中的实现本身运行良好,但有没有办法确定用户放置项目的顺序?
Here is an interesting use of JavaScript: reordering items with drag and drop. The implementation itself in my page works fine, but is there a way to determine in which order the user put the items?
我之所以这么问是因为我想在 cookie 中加载和保存商品订单.
I'm asking because I want to load and save the item order in a cookie.
推荐答案
UPDATED 2012
UPDATED 2012
获取元素的索引位置尝试读取这个:
get the index position of the elements try to read this:
jquery 的 COOKIE 插件:
COOKIE plugin for jquery:
JQUERY:
$(function() {
//coockie name
var LI_POSITION = 'li_position';
$('ul#sortable').sortable({
//observe the update event...
update: function(event, ui) {
//create the array that hold the positions...
var order = [];
//loop trought each li...
$('#sortable li').each( function(e) {
//add each li position to the array...
// the +1 is for make it start from 1 instead of 0
order.push( $(this).attr('id') + '=' + ( $(this).index() + 1 ) );
});
// join the array as single variable...
var positions = order.join(';')
//use the variable as you need!
alert( positions );
// $.cookie( LI_POSITION , positions , { expires: 10 });
}
});
});
HTML:
<ul id="sortable">
<li id="id_1"> Item 1 </li>
<li id="id_2"> Item 2 </li>
<li id="id_3"> Item 3 </li>
<li id="id_4"> Item 4 </li>
<li id="id_5"> Item 5 </li>
</ul>
PHP:
这只是一个例子,但你明白了:你可能想改用数据库并使用 AJAX 来取回 lis:
this is just an example but you got the idea: you may want use a database instead and use AJAX for get back the lis:
<?php
//check if cookie is set..
if ( isset( $_COOKIE['li_position'] ) ) {
//explode the cockie by ";"...
$lis = explode( ';' , $_COOKIE['li_position'] );
// loop for each "id_#=#" ...
foreach ( $lis as $key => $val ) {
//explode each value found by "="...
$pos = explode( '=' , $val );
//format the result into li...
$li .= '<li id="'.$pos[0].'" >'.$pos[1].'</li>';
}
//display it
echo $li;
// use this for delete the cookie!
// setcookie( 'li_position' , null );
} else {
// no cookie available display default set of lis
echo '
<li id="id_1"> Fuji </li>
<li id="id_2"> Golden </li>
<li id="id_3"> Gala </li>
<li id="id_4"> William </li>
<li id="id_5"> Jordan </li>
';
}
?>
这篇关于jQuery UI 可排序:确定项目的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!