简体   繁体   中英

Allow default action for target event and prevent default action for parent

We have this kind of markup:

<a href="#">
   <input type="file" />
</a>

By default when you click on input "Select file" window appears and location changes to "#". How do I prevent browser from changing location?

What I have tried:

//location still changes
$('input').bind('click', function (e) {
  e.stopPropagation();
});

//prevents "Select file" window
$('input').bind('click', function (e) {
  e.preventDefault();
});

//prevents "Select file" window 
$('a').bind('click', function (e) {
  e.preventDefault();
});

Try changing $(e) to e.

e.preventDefault();

When doing $(e).preventDefault() causes error

Uncaught TypeError: Object [object Object] has no method 'preventDefault' 

You need to check if the user has clicked on the a element and not the input file. This should work.

$('a').click(function(e) {
    if ($(e.target).is('a')) {
        e.preventDefault();
    }
});

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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