当我想在某个事件被触发后阻止其他事件处理程序执行时,我可以使用两种技术之一.我将在示例中使用jQuery,但这也适用于plain-JS:
event.preventDefault()$('a').click(function (e) {
// custom handling here
e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
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
我有一个input type="image".这类似于Microsoft Excel中的单元格注释.如果有人在input-image与之配对的文本框中输入一个数字,我会为其设置一个事件处理程序input-image.然后当用户点击时image,他们会得到一些弹出窗口,为数据添加一些注释.
我的问题是,当用户在文本框中输入零时,我需要禁用input-image事件处理程序.我试过以下,但无济于事.
$('#myimage').click(function { return false; });
Run Code Online (Sandbox Code Playgroud) 下面的解决方案是向下滑动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) 我在悬停状态下动态创建元素时遇到问题.当我将鼠标悬停在新创建的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/