简体   繁体   中英

Click event on <a> tag doesn't work in JQuery

I'm trying to alter a click event on my <a> tag.

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JQuery test</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $(document).ready(function () { alert('doc. ready'); $('#id_product_quick').on('click', function (e) { alert('click'); e.preventDefault(); loading(); }) }); </script> </head> <body> <a id="#id_product_quick" class="col-md-4" href="/scr/quick/3/"><img style="width: 200px" src="/static/img/icons/Button.png"></a> </body> </html> 

The JavaScript loads and alerts $(document).ready with success, but when I click on the <a> tag, I'm redirected to the original href when I want to escape the default action or alert 'click'.

Can anybody help me with my problem?

Remove # from Id attribute of HTML.

<a id="id_product_quick" class="col-md-4" href="/scr/quick/3/"><img style="width: 200px" src="/static/img/icons/Button.png"> </a>

or, Escape meta-character # with \\\\ from selector while attaching event handler

$('#\\#id_product_quick').on('click', function (e) {
    alert('click');
    e.preventDefault();
    loading();
})

See Docs

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\\\.

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