【问题标题】:function within a jQuery pluginjQuery插件中的函数
【发布时间】:2011-11-28 14:51:28
【问题描述】:

我写了一个插件,允许用户选择表格单元格:

https://jsfiddle.net/leeprice/Neftr/

我已经完成了主要功能,但是,我有一个问题。我需要能够将selected 函数作为插件选项传递。你会看到我在小提琴中评论的地方。

问题是,该函数应该只在mouseDown = 1时执行,但它在mousemove时执行

任何帮助表示赞赏:)

【问题讨论】:

  • 对,那有什么问题呢? selected 不应该用引号括起来。
  • @RichardD 问题是,该函数应该只在 mouseDown = 1 时执行,但它在 mousemove 时执行
  • 您可能应该在您的问题中提到这一点;)

标签: jquery function jquery-plugins


【解决方案1】:

使用初始化:

$('table').cellSelect({selected: function() { 
                                    alert('selected'); }
                              });

并调用您的处理程序:

// Needs to execute here
if (options.selected)
    options.selected();
}

代码:https://jsfiddle.net/Neftr/6/

【讨论】:

  • 问题是,该函数应该只在mouseDown = 1时执行,但它在mousemove时执行
  • 这是因为你已经将处理程序直接添加到mousemove:}).mousemove(options.selected).click(function() {。试试这个:jsfiddle.net/Neftr/9
  • 而这个触发的事件少了一点:jsfiddle.net/Neftr/11。但是你仍然需要调试它。
  • 到达那里 :) 但是如果我希望函数像这样$(this).text('selected') 这样所选表格单元格的文本将会改变。这可能吗?
  • 是的,只需在调用函数时作为参数this 传递,您将能够获取触发onmousemove 事件的元素。
【解决方案2】:

将您的选项更改为

selected: function() {

}

所以在调用插件时你可以这样做

$('table').cellSelect({
    selected:function() {
        alert('b');
    }
});

【讨论】:

    【解决方案3】:

    给你:https://jsfiddle.net/maniator/Neftr/3/

    只需使用options.selected

    【讨论】:

    • 问题是,该函数应该只在mouseDown = 1时执行,但它在mousemove时执行
    • 是的,但它也在 if(mouseDown === 1) 语句中
    【解决方案4】:

    我已经更新了你的小提琴here

    相关改动:

    在初始化中你传递匿名函数:

    $(function() {
        $('table').cellSelect({ selected: function() { alert("foo"); }});
    });
    

    然后在需要时,运行分配给options.selected参数的函数:

    if (mouseDown === 1) {
        if (shiftDown === 1) {
            $(this).removeClass('selected');
        } else {
            $(this).addClass('selected');
            options.selected; // run passed anonymous function, or default specified one.
        }
    }
    

    【讨论】:

    • 但问题是,该函数只应该在mouseDown = 1时执行,但它在mousemove时执行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多