jQuery stopPropagation not working when applied to

2019-05-29 00:21发布

hope you can help me. I have html markup like this:

<a href="error.htm" class="button" id="_uiStart" style="-moz-border-radius: 4px 4px 4px 4px;">
<span>Start</span>
<input type="text" id="_uiCode">
</a>

Normaly, when user clicks on the textbox, the page redirects to "error.htm". I wanted to prevent that so I use jQuery to cancel that:

$(document).ready(function() {
   var mute = function(event){        
       event.stopPropagation();
   };    
   $('a.button input').click(mute)
    .mousedown(mute)
    .mouseup(mute);
}

However, this does not work, the click still gets processed by anchor and redirects to "error.htm".

Please help, thank you.

2条回答
该账号已被封号
2楼-- · 2019-05-29 01:06

edited after omittones's comment:

why not doing

$('a.button input').click(function() { $(this).focus(); return false;});

This will prevent the normal event from happening. event.stopImmediatePropagation (which is as far as I know the way to stop Propagation) stops the event from bubbling up through the hierarchy of your code. If this doesn't work in all browsers, just do both.

$('a.button input').click(function() {
    $(this).focus(); // added this line after editing
    e.stopImmediatePropagation();
    return false;
});
查看更多
趁早两清
3楼-- · 2019-05-29 01:20

Return false instead (working fiddle)

stopPropagation is only for event handlers, not default behavior.

preventDefault does what you want, but returning false triggers both.

Updated fiddle:

Add $(this).focus() before returning and you should be golden. I would however suggest you look at another way of setting up your html so the <a> doesn't wrap the input in the first place.

查看更多
登录 后发表回答