相关疑难解决方法(0)

event.preventDefault()与return false

当我想在某个事件被触发后阻止其他事件处理程序执行时,我可以使用两种技术之一.我将在示例中使用jQuery,但这也适用于plain-JS:

1. event.preventDefault()

$('a').click(function (e) {
    // custom handling here
    e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

2. return false

$('a').click(function () {
    // custom handling here
    return false;
});
Run Code Online (Sandbox Code Playgroud)

这两种停止事件传播的方法之间有什么显着差异吗?

对我来说,return false;比执行方法更简单,更短并且可能更不容易出错.使用该方法,您必须记住正确的套管,括号等.

另外,我必须在回调中定义第一个参数才能调用该方法.也许,有一些原因可以解释为什么我应该避免这样做并使用preventDefault呢?有什么更好的方法?

javascript jquery event-handling event-propagation dom-events

2891
推荐指数
9
解决办法
81万
查看次数

在jQuery中删除事件处理程序的最佳方法?

我有一个input type="image".这类似于Microsoft Excel中的单元格注释.如果有人在input-image与之配对的文本框中输入一个数字,我会为其设置一个事件处理程序input-image.然后当用户点击时image,他们会得到一些弹出窗口,为数据添加一些注释.

我的问题是,当用户在文本框中输入零时,我需要禁用input-image事件处理程序.我试过以下,但无济于事.

$('#myimage').click(function { return false; });
Run Code Online (Sandbox Code Playgroud)

jquery html-input

1038
推荐指数
14
解决办法
69万
查看次数

jQuery - 禁用单击直到所有链接的动画完成

下面的解决方案是向下滑动groupDiv显示div1和足够的空间让div2滑入.这都是通过链接#Link.Click()元素上的动画来实现的.

但是,当快速点击链接时,似乎会出错.有办法防止这种情况吗?通过禁用Click功能,直到链式动画完成?我目前有检查,但他们似乎没有做这项工作:(

这是我正在使用的代码:

自定义动画功能.


//Slide up or down and fade in or out
jQuery.fn.fadeThenSlideToggle = function(speed, easing, callback) {
    if (this.is(":hidden")) {
        visibilityCheck("show", counter--);
        return this.slideDown({duration: 500, easing: "easeInOutCirc"}).animate({opacity: 1},700, "easeInOutCirc", callback);
    } else {
        visibilityCheck("hide", counter++);
        return this.fadeTo(450, 0, "easeInOutCirc").slideUp({duration: 500, easing: "easeInOutCirc", complete: callback});
    }
};

//Slide off page, or into overflow so it appears hidden.
jQuery.fn.slideLeftToggle = function(speed, easing, callback) {
    if …
Run Code Online (Sandbox Code Playgroud)

javascript jquery

25
推荐指数
2
解决办法
3万
查看次数

如何使jQuery 1.7 .on()悬停?

我在悬停状态下动态创建元素时遇到问题.当我将鼠标悬停在新创建的html元素上时,它不起作用.

这是我的HTML代码:

<button id="create">create new button</button>
<button class="hover">hover me</button>
<div></div>
Run Code Online (Sandbox Code Playgroud)

jQuery的:

var createBtn = $("#create");

createBtn.click(function() {
    $('div').append('<button class="hover">new hover button</button');  
    return false;        
}); 


$('.hover').hover(function() {
    alert('you hovered the button!');
}, function() {
    alert('you removed the hover from button!');
});
Run Code Online (Sandbox Code Playgroud)

我甚至试过这段代码:

$('.hover').on({
    mouseenter : function() {
         alert('you hovered the button!');
    },
    mouseleave : function() {
        alert('you removed the hover from button!');
    }

});
Run Code Online (Sandbox Code Playgroud)

如图所示http://api.jquery.com/on/,但仍然没有运气.这里也是演示:http://jsfiddle.net/BQ2FA/

jquery hover

8
推荐指数
1
解决办法
1万
查看次数