简体   繁体   English

为什么我不能停止点击的默认操作?

[英]Why can't I stop the default action on my click?

I have the following: 我有以下内容:

$("#city-button-panel a")
    .click(function () {
    preventDefault();
    var $link = $(this);
    getCityContentAjax($link);
});

But it's not allowing me to preventDefault and it gives a syntax error 但它不允许我阻止默认,它会给出语法错误

Here is what the elements look like that are deep inside #city-button-panel: 以下是#city-button-panel内部的元素:

<a href="/City/1555009O" id="btn-49">49</a>

You need to call preventDefault on the event you're being passed. 您需要在传递的事件上调用preventDefault Any other preventDefault is either undefined or does something else. 任何其他preventDefault要么未定义,要么做其他事情。 Try: 尝试:

$("#city-button-panel a")
        .click(function (event) {
            event.preventDefault(); 
            var $link = $(this);
            getCityContentAjax($link);
        });

Demo: http://jsfiddle.net/vatjK/ 演示: http//jsfiddle.net/vatjK/

Note that the handler has to return successfully in order for the preventDefault to work. 请注意,处理程序必须成功返回才能使preventDefault工作。 If getCityContentAjax throws an exception, the default action can not be prevented without also preventing the exception from propagating. 如果getCityContentAjax抛出异常,则在不阻止异常传播的情况下也无法阻止默认操作。 You can, however, do this (if you can't fix getCityContentAjax ): 但是,您可以这样做(如果您无法修复getCityContentAjax ):

$("#city-button-panel a")
        .click(function (event) {
            event.preventDefault(); 
            var $link = $(this);
            try{
                getCityContentAjax($link);
            }catch(e){
                console && console.error(e);
                alert("Look at the console!!!"); // optional
            }
        });

There is no syntax error in this piece of code. 这段代码中没有语法错误。 If the browser thinks otherwise, you may have syntax error before the code. 如果浏览器另有说法,则可能在代码之前出现语法错误。 Note there's a difference between a syntax error (unmatched parentheses and such) and a reference error (a function in the global scope does not exist). 请注意,语法错误(不匹配的括号等)与引用错误(全局范围内的函数不存在)之间存在差异。

here is plain javascript (+html) version 这里是普通的javascript(+ html)版本

<head>
  <script>
     function theClick(url,ev){
       getCityContentAjax(url);
       ev.preventDefault();
     }
  </script>
</head>

<body>
  <a onclick="theClick(this,event)" href="url.html">a link</a>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM