我在这里缺少什么?
请注意:使用 jQuery MOBILE
如果我使用preventDefault,页面加载就像我只有链接而没有脚本一样,当我更改为return false(我总是在普通JS onclick事件处理程序上使用它)时,它会按预期工作。 我已经浏览过其他帖子,所有帖子都使用 .click 并且都建议 PreventDefault。
$(document).ready(function() {
$("#leftdiv a").on("click",function(e) {
$("#rightDiv").load(this.href);
return false; // I was sure preventDefault would work
});
});
HTML
<div id="leftdiv" style="position:absolute;padding-right:5%; overflow:scroll;">
<a href="page1.htm">Launch page 1</a><br />
<a href="page2.htm">Launch page 2</a>
</div>
<div id="rightDiv" style="padding-left:30%"></div>
最佳答案
e.preventDefault();
没用?
$('a').on("click",function(e){ //do something e.preventDefault(); });
将 e.preventDefault();
放在代码的顶部或末尾通常并不重要。我猜还有方法e.stop()
。但是,当它对您有用时,为什么不坚持使用 return false;
呢?
来自 jQuery 移动文档:
Canceling an elements default click behavior
Applications can call preventDefault() on a vclick event to cancel an element's default click behavior. On mouse based devices, calling preventDefault() on a vclick event equates to calling preventDefault() on the real click event during the bubble event phase. On touch based devices, it's a bit more complicated since the actual click event is dispatched about 300ms after the vclick event is dispatched. For touch devices, calling preventDefault() on a vclick event triggers some code in the vmouse plugin that attempts to catch the next click event that gets dispatched by the browser, during the capture event phase, and calls preventDefault() and stopPropagation() on it. As mentioned in the warning above, it is sometimes difficult to match up a touch event with its corresponding mouse event because the targets can differ. For this reason, the vmouse plugin also falls back to attempting to identify a corresponding click event by coordinates. There are still cases where both target and coordinate identification fail, which results in the click event being dispatched and either triggering the default action of the element, or in the case where content has been shifted or replaced, triggering a click on a different element. If this happens on a regular basis for a given element/control, we suggest you use click for triggering your action.
function() {
return false;
}
// IS EQUAL TO
function(e) {
e.preventDefault();
e.stopPropagation();
}
来源: http://css-tricks.com/return-false-and-prevent-default/
似乎还支持 .on()
,因为不支持 document.ready
关于jquery - "on"防止默认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9698003/