jQuery preventDefault() 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5614099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:29:23  来源:igfitidea点击:

jQuery preventDefault() not working

javascript-eventsevent-handlingjquery

提问by pufos

I have the following code:

我有以下代码:

$(document).ready(function(){

    $("div.subtab_left li.notebook a").click(function(event) {
    event.preventDefault();
    return false;   
    });

});

but when I click the element .. it doesn't prevent the default action .. Why?

但是当我单击元素时.. 它不会阻止默认操作.. 为什么?

and when modifying the code to:

并在将代码修改为:

$(document).ready(function(){

    $("div.subtab_left li.notebook a").click(function() {
    e.preventDefault();
    alert("asdasdad");
    return false;   
    });

});

it stops the default action but does not alert .. I couldn't find any answer on jQuery docs.

它会停止默认操作,但不会发出警报.. 我在 jQuery 文档上找不到任何答案。

The full code goes like this:

完整的代码是这样的:

$(document).ready(function(){

$('#tabs div.tab').hide();
$('#tabs div.tab:first').show();
$('#tabs ul li:first').addClass('active');

$('#tabs ul li a').click(function(){
$('#tabs ul li').removeClass('active');
$(this).parent().addClass('active');
var currentTab = $(this).attr('href');
$('#tabs div.tab').hide();
$(currentTab).show();
return false;
});

    $("div.subtab_left li.notebook a").click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();

    alert("asdasdad");
    return false;

    });

});

and the HTML structure is:

并且 HTML 结构是:

<div id="tabs">
<ul id="nav">
<li><a id="tab1" href="#tab-1"></a></li>
<li><a id="tab2" href="#tab-2"></a></li>
<li><a id="tab3" href="#tab-3"></a></li>
<li><a id="tab4" href="#tab-4"></a></li>
</ul>

<div class="tab" id="tab-1">
        <script type="text/javascript">$(document).ready(function(){$("ul.produse li").hover(function () {
        $("ul.produse li").removeClass('active');$(this).addClass('active');}, function () {$(this).removeClass('active');});});
    </script>

    <div class="subtab_left"> 
        <ul>
            <li class="notebook"><a href="#">1</a></li>
            <li class="netbook"><a href="#">2</a></li>      
            <li class="allinone"><a href="#">2</a></li> 
            <li class="desktop"><a href="#">2</a></li> 
            <li class="procesoare"><a href="#">2</a></li> 
            <li class="placi_video"><a href="#">2</a></li>    
            <li class="hdd_desktop"><a href="#">2</a></li>
            <li class="tv_plasma"><a href="#">2</a></li>
            <li class="tv_lcd"><a href="#">2</a></li>
            <li class="telefoane_mobile last_item"><a href="#">2</a></li>
        </ul>
    </div>

回答by no.good.at.coding

Update

更新

And there's your problem - you dohave to click event handlers for some aelements. In this case, the order in which you attach the handlers matters since they'll be fired in that order.

还有你的问题-你必须单击事件处理程序的一些a元素。在这种情况下,附加处理程序的顺序很重要,因为它们将按该顺序被触发。

Here's a working fiddlethat shows the behaviour you want.

这是一个显示您想要的行为的工作小提琴

This should be your code:

这应该是你的代码:

$(document).ready(function(){


    $('#tabs div.tab').hide();
    $('#tabs div.tab:first').show();
    $('#tabs ul li:first').addClass('active');

    $("div.subtab_left li.notebook a").click(function(e) {
        e.stopImmediatePropagation();
        alert("asdasdad");
        return false;
    });

    $('#tabs ul li a').click(function(){
        alert("Handling link click");
        $('#tabs ul li').removeClass('active');
        $(this).parent().addClass('active');
        var currentTab = $(this).attr('href');
        $('#tabs div.tab').hide();
        $(currentTab).show();
        return false;
    });

});

Note that the order of attaching the handlers has been exchanged and e.stopImmediatePropagation()is used to stop the other click handler from firing while return falseis used to stop the default behaviour of following the link (as well as stopping the bubbling of the event. You may find that you need to use only e.stopPropagation).

请注意,附加处理程序的顺序已交换,e.stopImmediatePropagation()用于阻止其他点击处理程序触发,而return false用于停止跟随链接的默认行为(以及停止事件的冒泡。您可能会发现您只需要使用e.stopPropagation)。

Play around with this, if you remove the e.stopImmediatePropagation()you'll find that the second click handler's alert will fire after the first alert. Removing the return falsewill have no effect on this behaviour but will cause links to be followed by the browser.

试试这个,如果您删除 ,e.stopImmediatePropagation()您会发现第二个点击处理程序的警报将在第一个警报之后触发。删除return false不会对此行为产生影响,但会导致浏览器跟踪链接。

Note

笔记

A better fix might be to ensure that the selectors return completely different sets of elements so there is no overlap but this might not always be possible in which case the solution described above might be one way to consider.

更好的解决方法可能是确保选择器返回完全不同的元素集,因此没有重叠,但这可能并不总是可行的,在这种情况下,上述解决方案可能是一种考虑方式。



  1. I don't see why your first code snippet would not work. What's the default action that you're seeing that you want to stop?

    If you've attached other event handlers to the link, you should look into event.stopPropagation()and event.stopImmediatePropagation()instead. Note that return falseis equivalent to calling both event.preventDefaultandevent.stopPropagation()ref

  2. In your second code snippet, eis not defined. So an error would thrown at e.preventDefault()and the next lines never execute. In other words

    $("div.subtab_left li.notebook a").click(function() {
        e.preventDefault();
        alert("asdasdad");
        return false;   
    });
    

    should be

    //note the e declared in the function parameters now
    $("div.subtab_left li.notebook a").click(function(e) {
        e.preventDefault();
        alert("asdasdad");
        return false;   
    });
    
  1. 我不明白为什么你的第一个代码片段不起作用。您看到要停止的默认操作是什么?

    如果您已将其他事件处理程序附加到链接,则应查看event.stopPropagation()event.stopImmediatePropagation()。请注意,return false相当于同时调用event.preventDefaultevent.stopPropagation()ref

  2. 在您的第二个代码片段中,e未定义。所以会抛出错误e.preventDefault()并且下一行永远不会执行。换句话说

    $("div.subtab_left li.notebook a").click(function() {
        e.preventDefault();
        alert("asdasdad");
        return false;   
    });
    

    应该

    //note the e declared in the function parameters now
    $("div.subtab_left li.notebook a").click(function(e) {
        e.preventDefault();
        alert("asdasdad");
        return false;   
    });
    

Here's a working exampleshowing that this code indeed does work and that return falseis not really required if you only want to stop the following of a link.

这是一个工作示例,表明此代码确实有效,return false如果您只想停止链接的以下内容,则不需要这样做。

回答by Blerim J

Try this one:

试试这个:

   $("div.subtab_left li.notebook a").click(function(e) {
    e.preventDefault();
    return false;   
    });

回答by ?ime Vidas

Try this:

尝试这个:

$("div.subtab_left li.notebook a").click(function(e) {
    e.preventDefault();
});

回答by chroda

If you already test with a submit action, you have noticed that not works too.

如果您已经使用提交操作进行测试,您会注意到这也不起作用。

The reason is the form is alread posted in a $(document).read(...

原因是表格已经张贴在 $(document).read(...

So, all you need to do is change that to $(document).load(...

因此,您需要做的就是将其更改为 $(document).load(...

Now, in the moment of you browaser load the page, he will execute.

现在,在浏览器加载页面的那一刻,他将执行。

And will work ;D

并且会工作;D

回答by northK

i just had the same problems - have been testing a lot of different stuff. but it just wouldn't work. then i checked the tutorial examples on jQuery.com again and found out:

我只是遇到了同样的问题 - 一直在测试很多不同的东西。但这行不通。然后我再次检查了 jQuery.com 上的教程示例,发现:

your jQuery script needs to be afterthe elements you are referring to !

您的 jQuery 脚本需要您所指的元素之后

so your script needs to be after the html-code you want to access!

所以你的脚本需要在你想要访问的 html 代码之后!

seems like jQuery can't access it otherwise.

否则 jQuery 似乎无法访问它。

回答by Antoine Subit

If e.preventDefault();is not working you must use e.stopImmediatePropagation();instead.

如果e.preventDefault();不起作用,则必须e.stopImmediatePropagation();改用。

For further informations take a look at : What's the difference between event.stopPropagation and event.preventDefault?

有关更多信息,请查看: event.stopPropagation 和 event.preventDefault 之间有什么区别?

$("div.subtab_left li.notebook a").click(function(e) {
    e.stopImmediatePropagation();
});