jQuery防止目标父级内部的链接默认



我有以下标记:

<div id="someID" class="target-class">
   ....
   <a href="#page1">
     ....
   </a>
</div>

我正在使用Zepto来瞄准"目标级"以应用双水龙头,但我不希望触发链接。这是我的JS代码:

$(document).ready(function() {
    $(".target-class").live("doubleTap", function(e) {
         e.preventDefault();
         e.stopPropagation();
         var a = $(this).attr("id");
         // do something here
    });
    $("a").live("click", function(e) {
         // do something with all my links
    });
});

但是,所有这些触发了链接并更改URL模式(我正在使用PushState)。

这也在用于iOS和Android的Mobile Safari上。

有指导?

我能够将其与以下代码一起使用。基本上,您必须捕获并扔掉"常规"点击事件(确保停止传播并防止默认行为) - 这将停止默认链接行为。然后使用" Singletap"one_answers" DoubleTap"事件处理程序捕获并响应所需的事件。我在iOS 6上的Safari和Android 4.1的Chrome上对此进行了测试。

<!DOCTYPE html>
<html>
<head>
    <title>test doubletap</title>
    <meta name="viewport" content="initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no;" />
</head>
<style>
    body {
        font-size: 200%;
    }
    a {
        background-color: yellow;
    }
</style>
<body>
<div id="someID" class="target-class" style="height:200px;">
    text here in the div
    <a href="#page1">page1</a>
    <a href="#page2">page2</a>
    <a href="#page3">page3</a>
    more text here in the div
</div>
<div id="output"></div>

<script src="zepto.js"></script>
<script>
function log(input) {
    var html = $("#output").html();
    $("#output").html( html + "<br/>" + input.toString() );
}
$(document).ready(function() {
    $(".target-class").on("doubleTap", function(e) {
        //handle the double-tap event
        var a = $(this).attr("id");
        log(e.type + " - " + a);
        e.stopPropagation();
        e.preventDefault();
        return false;
    });
    $("a").on("click", function(e) {
        //throw away all link "click" events to prevent default browser behavior
        e.stopPropagation();
        e.preventDefault();
        return false;
    });
    $("a").on("singleTap", function(e) {
        //handle the single click and update the window location hash/fragment
        var a = $(event.target);
        var href = a.attr("href");
        log( e.type + ": " + href );
        window.location.hash = href;
        e.stopPropagation();
        e.preventDefault();
        return false;
    });
});
</script>
</body>
</html>

最新更新