JQuery无法绑定可选择的click事件

时间:2014-06-16 15:12:50

标签: javascript jquery jquery-ui onclick selectable

这应该非常简单,但我无法检索click事件并在JQuery UI的selectable项目上触发函数。

<div id="a">
<ol id="selectable-a">
  <li class="a-item">1</li>
  <li class="a-item">2</li>
  <li class="a-item">3</li>
  <li class="a-item">4</li>
</ol>
</div>

使用Javascript:

$("#selectable-a").selectable();

$("li .a-item").click(function () {
  console.log("Executing command");
});

但是click事件永远不会被触发。

我已经考虑了谷歌。

  • 尝试将.click(替换为.bind('click',,但不会改变任何内容
  • In the jquery forum他们提出了这个问题并且有人提出了一个解决内部功能的解决方案,这对我来说不起作用(content.data('selectable')总是未定义,无论如何)
  • 将距离设置为1,意味着用户需要将鼠标移动1个像素才能触发事件,这是一个坏主意。
  • This SO question没有任何满意的答案。也就是说,我并不想在所选项目上获取点击事件,而是在任何项目上。

关于如何解决问题的任何想法?

5 个答案:

答案 0 :(得分:4)

使用$("li.a-item")代替$("li .a-item")

第一个用a-item类查找li;第二个在list元素中查找带有a-item类的元素。

答案 1 :(得分:1)

这适用于:

<ol id="selectable-a">
  <li><div class="a-item">1</div></li>
</ol>

对于你的,请使用:

$("li.a-item").click(function () {
  console.log("Executing command");
});

甚至只是

$(".a-item").click(function () {
  console.log("Executing command");
});

如果您不在其他地方使用.a-item

答案 2 :(得分:1)

如果您使用以下jQuery选择器,它可以工作:

$("#selectable-a li").click(function () {
   console.log("Executing command");
});

这样做的另一个好处是,您不再需要为列表项添加额外的课程

示例:http://jsfiddle.net/9brPn/1/

答案 3 :(得分:1)

自动选择添加辅助div以显示类.ui-selectable-helper的套索。此辅助div位于鼠标右下方。我最好的猜测是它是在mousedown上创建的,然后干扰了点击。

我正在努力寻找更好的解决方案,但就目前而言,我正在使用它:

.ui-selectable-helper{
  pointer-events:none;
}

此外,将您的选择器更改为:$("li.a-item")而不是$(“li .a-item”)

  

[注意代码中的空格不正确]

[编辑] 更好的解决方法:来自http://api.jqueryui.com/selectable/#option-distance

将选项距离添加到初始化为$("#selectable-a").selectable({distance:10});

答案 4 :(得分:1)

我有同样的问题,兄弟!我找到了完美的解决方案:

我的代码是:

$( "#selectable" ).selectable();
$('li.slot').on('click', function() {
    var selected_date = $(this).attr('data');
    console.log('selected item: ' +  selected_date); // open the console to see the selected items after each click
    $('#appointment_start').val(selected_date);
});

现在是:

$( "#selectable" ).selectable({
    selected: function( event, ui ) {
        var selected_date = $(ui.selected).attr('data');
        console.log('selected item: ' +  selected_date); // open the console to see the selected items after each click
        $('#appointment_start').val(selected_date);
    }
});

对我来说,它很完美:)

相关问题