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

mit*_*737 2 jquery

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

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

现在我的问题是:

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

有什么建议?

提前致谢.

我的HTML标记是:

<ul id="ulSelectable" class="ui-selectable">
  <li id="196500" class="ui-selectee ui-selected">
    <div id="dvItem">
      <img id="Interest_lvResult_ctrl0_ctl00_imgInterest" src="Images/Pic1.jpg"/>
    </div>
    <div class="Profile_Interests_Card_ItemName"> Driver </div>
  </li>
  <li id="196600" class="ui-selectee">
    <div id="dvItem">
      <img id="Interest_lvResult_ctrl0_ctl01_imgInterest"  src="Images/Pic2.jpg" />
    </div>
    <div class="Profile_Interests_Card_ItemName"> Builder </div>
  </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

而我的javascript:

<script type="text/javascript">
    var setSelector = "#ulSelectable";
    $(function() {
        $(setSelector).selectable({ filter: 'li' });

    });
</script>
Run Code Online (Sandbox Code Playgroud)

Cod*_*lan 5

$( '#ulSelectable').find( '礼').removeClass( 'UI选择').END().find( '#196600').addClass( 'UI选择');

UI选择的

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

$('#ulSelectable')
.find('li')
  .removeClass('ui-selected')
  .end()
.find('#196600')
  .addClass('ui-selected');
Run Code Online (Sandbox Code Playgroud)

这假设您选择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);
});
Run Code Online (Sandbox Code Playgroud)

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