【问题标题】:JQuery UI Selectable find the <li> element in the list that the user clicked onJQuery UI Selectable 在用户点击的列表中找到 <li> 元素
【发布时间】:2014-12-12 15:54:57
【问题描述】:

我希望能够在可选的 jQueryUI 中获取用户单击的 &lt;li&gt; 元素。这是因为我想找出他们点击的元素是否已经被选中,然后根据它做一些事情。这是我工作的代码:

$(document).ready(function() // Execute all of this on load 
  {
    // Add week selector
    $(function() {
      var startElementSelected = false;

      $("#popupWeeks").selectable({
        start: function(e) {
          var classSelected = e.toElement.className.search("ui-selected");

          if (classSelected != -1) {
            startElementSelected = true;
          } else {
            startElementSelected = false;
          }
        }
      });
    });
  });

问题是这适用于 chrome,但不适用于 Firefox,我可以用它来为两者都工作。我寻找了相当于e.toElement.className 的firefox,但找不到任何东西,而且我在点击事件的事件处理方面遇到了麻烦。

非常感谢任何帮助。

【问题讨论】:

  • 如果您使用的是 jQuery,那么为什么不使用 jQuery?使用.hasClass("ui-selected") 而不是e.toElement.className.search("ui-selected");

标签: jquery selectable


【解决方案1】:

jQuery 的主要优点之一是它可以在后台为您处理不同的浏览器不一致问题,因此您可能也应该在这种情况下使用它。

由于 jQuery selectable 将 ui-selected 类赋予选定(单击)元素,您可以做的是在具有该类的 selectable 中找到 li 元素。例如:

$('#popupWeeks li.ui-selected');

或者您可以检查元素是否具有所需的类,例如:

element.hasClass('ui-selected');

Here is a fiddle example

编辑:

根据您的评论,我相信您可以解决您需要的方法是跟踪某些结构中的选定元素。

然后根据用户行为添加/删除元素。

我决定使用数组来实现:

 var selectedItems = [];                                   // array to hold currently selected items

 $( 'li.ui-widget-content' ).on('click', function() {

     var id = $(this).attr('id'),
         isSelected = $(this).hasClass('ui-selected');

     if(selectedItems.indexOf(id) != -1) {                 // if element already selected, alert us
         alert('Product #' + id + ' was already clicked');   
     } else if(isSelected) {                               // if element selected for first time
         selectedItems.length = 0;                         // clear the array
         $('.ui-selected').each(function() {
             selectedItems.push($(this).attr('id'));       // add all the selected items
         });
     } else {                                              // otherwise element is unselected and we remove it
         selectedItems.splice(selectedItems.indexOf(id), 1);   
     }
     console.log('selected items: ' + selectedItems);      // open the console to see the selected items after each click
 });

Here is a fiddle example

【讨论】:

  • 你在 jsfiddle 中发布的函数我该放在哪里?我尝试使用它,单击时它不会发出任何警报。我在 chrome 中使用了调试器并为该函数设置了断点,它甚至似乎都没有运行它。虽然在 jsfiddle 中工作。
  • 我尝试使用此功能并在加载时运行它(当我调试时),但是当我单击它时它不会运行它。我在哪里把这个函数放在脚本中?例如$document.ready 之前/之后还是其他地方?这是我所拥有的:pastebin.com/qtv2kPnA
  • 所有内容都应该在document.ready 中。你应该read this page
  • 这真的变成了一个不同的问题,但我快到了,我有这个文件:pastebin.com/xv41LJyM 并且它不起作用,但我将它发布到 jsfiddle 并且它可以吗? jsfiddle.net/4w7twgwo/14
猜你喜欢
  • 2015-08-29
  • 1970-01-01
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 2021-04-02
  • 1970-01-01
相关资源
最近更新 更多