jquery - "on"防止默认

标签 jquery jquery-mobile event-handling

我在这里缺少什么?

请注意:使用 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

来源: http://jquerymobile.com/test/docs/api/events.html

关于jquery - "on"防止默认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9698003/

相关文章:

jquery - 仅在可见时按 Enter 键使按钮可用

javascript - 将函数结果分配为 ​​HTML ID

javascript - 清空 Javascript 对象 (Jquery Mobile)

javascript - 在新选项卡中打开新网页后,如何获取书签中的 JavaScript 代码以执行?

c# - 如何在 WPF 中为所有窗口(整个应用程序)设置事件处理程序?

c# - 为什么尝试在WPF/C#中注册所有事件时出现构建错误?

javascript - jQueryMobile 无法获取 iPhone 上输入文本框的值

css - jQuery Mobile 更改背景图像

jquery - 获取 jQuery mobile 中选项按钮的值

JQuery - 从同一父元素的另一个子元素检索值