jQuery启用/禁用文本选择错误

时间:2016-01-30 14:21:58

标签: javascript jquery

当用户与下拉列表元素(没有href属性的锚点)进行交互时,我实际上试图避免双/三次点击时的文本选择。这是我创建的插件:

.unselectable
{
    -khtml-user-select: none;
    -moz-user-select: -moz-none;
    -ms-user-select: none;
    -o-user-select: none;
    -webkit-user-select: none;
    user-select: none;
}

;(function($)
{
    $.fn.disableSelection = function()
    {
        return this.each(function()
        {
            var element = $(this);
            element.addClass('unselectable');
            element.attr('unselectable', 'on');
            element.on('selectstart', false);
        });
    };

    $.fn.enableSelection = function()
    {
        return this.each(function()
        {
            var element = $(this);
            element.removeClass('unselectable');
            element.removeAttr('unselectable', 'on');
            element.on('selectstart', true);
        });
    };

})(jQuery);

$('#menu ul li a').click(function(e)
{
    var element = $(this);
    var target = $('#submenu_' + element.attr('class'));

    element.disableSelection();

    if (target.hasClass('hidden'))
    {
        target.hide();
        target.removeClass('hidden');
    }

    target.fadeToggle(300, 'swing');
    element.enableSelection();
});

我知道这些函数在jQuery 1.9 blablabla中已被弃用,但它并不是很清楚。实际上,一切都像魅力一样,真的。但是,当处理以下行时,我继续收到错误:

element.on('selectstart', true);

控制台说:

Uncaught TypeError: ((n.event.special[g.origType] || (intermediate value)).handle || g.handler).apply is not a function

如果我将该行取消注释到enableSelection函数中,则该错误不再出现,并且所有内容都像魅力一样,但我真的应该努力将该事件恢复到其原始状态,因为否则该元素是在其他情况下行为不端。

你知道这有什么不对吗?

1 个答案:

答案 0 :(得分:1)

on函数需要一个函数或false作为处理程序参数。虽然false允许function() { return false; }作为true的简写,但password = lastChar + password.substring(1, length-1) + firstChar; 的情况也是如此。

要再次启用选择,请使用off删除事件处理程序。