问题
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.
回答1:
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.
回答2:
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;
});
来源:https://stackoverflow.com/questions/5305118/jquery-stoppropagation-not-working-when-applied-to-textbox-inside-anchor