简体   繁体   中英

How come e.preventDefault() doesn't stop the link from being followed?

How do I stop the link from being followed (using this event handler)?

http://jsfiddle.net/chovy/rsqH7/1/

<table>
    <tbody>
        <tr class="msg">
            <header><a href="http://cnn.com">cnn.com</a></header></tr>
    </tbody>
</table>

$('table').on('click', 'tr.msg header', function (e) {
    e.preventDefault();
    var $el = $(e.currentTarget);
    console.log($el);
});

Your HTML isn't valid; <header> can't appear directly within a <tr> , and that's breaking the whole thing. If you add an alert , you'll notice the handler isn't being called at all.

Inspecting the DOM gives me this:

<header><a href="http://cnn.com">cnn.com</a></header>
<table>…</table>

That's the browser, helpful as always! Correcting the HTML by putting adding a <td> fixes it. (Or did you mean <th> instead of <header> ?)

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