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

时间:2009-05-14 04:40:01

标签: jquery

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

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

现在我的问题是:

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

    提前致谢。

    我的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>
    

    我的javascript:

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

2 个答案:

答案 0 :(得分:5)

$( '#ulSelectable') .find( '礼')   .removeClass( 'UI选择')   。结束() .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');

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

要获得以后存储的值,您必须首先知道您实际需要的值。它是图像src还是具有类“Profile_Interests_Card_ItemName”的div的值,例如你想要“建造者”或“司机”。让我们假设你想要更晚。所以我的想法是在你的表单上提交你添加一个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”的字段中传递到您的服务器。

答案 1 :(得分:1)

要点击要使用document.ready函数的第一个加载,该函数在页面和DOM加载之后调用,例如

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