jQuery selectable:如何在第一次加载时选择项目

我使用jQuery selectable来选择.net listview中的项目。 用户可以选择他想要的项目,并可以通过单击保存按钮进行保存。 下次当用户来到页面时,他将能够看到他之前选择的项目。

使用jQuery selectable插件用户可以通过单击选择项目。

现在我的问题是:

  1. 如何在第一次加载时显示现有的选定项目?
  2. 选择项目后如何从代码页面后面获取所选项目的值,以便将其保存到数据库中?

有什么建议?

提前致谢。

我的HTML标记是:

  • Driver
  • Builder

而我的javascript:

  var setSelector = "#ulSelectable"; $(function() { $(setSelector).selectable({ filter: 'li' }); });  

$(’#ulSelectable’)。find(’li’)。removeClass(’ui-selected’)。end()。find(’#196600’)。addClass(’ui-selected’);

UI选择的

好的,所以看起来你只想将CSS类“ui-selected”添加到你想要选择的li(你已经存储在数据库中或哪里)? 它是否正确? 如果是这样,基本方法是首先从所有元素中删除该类(例如,在上面的HTML中,该类在第一个li上,但是让我们想要选择的那个是第二个)。 所以我们首先从所有li元素中删除它,然后将其添加到所需的元素中。 jQuery会是这样的:

 $('#ulSelectable') .find('li') .removeClass('ui-selected') .end() .find('#196600') .addClass('ui-selected'); 

这假设您正在选择DOM ID为“196600”的第二个li。 您当然会在页面渲染时替换它。

要获得以后存储的值,您必须首先知道您实际需要的值。 它是图像src还是具有类“Profile_Interests_Card_ItemName”的div的值,例如,您需要“Builder”或“Driver”。 让我们假设你想要更晚。 因此,我们的想法是,在您的表单提交中添加一个jQuery事件来解析您的DOM,然后获取所选项并将其放入隐藏的表单字段,然后将其提交给后端。

假设您的表单的DOM ID为“the_form”,并且您有一个名为“type”的(最初为空)隐藏表单字段,其ID为“job_type”:

 $('#the_form').submit(function(n) { //grab the LI that is selected var li = $('#ulSelectable').find('li.ui-selected'); //now find the div with our class within this li and grab its inner text var job_type = li.find('div.Profile_Interests_Card_ItemName').text(); //set the hidden field $('#job_type').val(job_type); }); 

现在,您有一个隐藏的表单字段,其中包含“Profile_Interests_Card_ItemName”类的内容,它将在名为“type”的字段中传递到您的服务器。

要进入第一个加载,你想要使用在页面和DOM加载之后调用的document.ready函数

 $(document).ready(function(n) { // your code will be executed here after the DOM loads });