简体   繁体   中英

event.preventDefault not working as it should

I loaded data using AJAX in a div.

<div id="container">
<a class="hello" href="abc.php">hello</a>   // loaded using ajax
<div>

Now I have jQuery:

<script type="text/javascript" charset="utf-8">
  $(document).ready(function() {
 $('.hello').on("click",function(e){
 e.preventDefault();
 });
 });
 </script>

However it's not working as it should, ie it's directing me to abc.php . Where am I going wrong ?

Use .on as your a tag is loaded dynamically

$('#container').on("click",".hello",function(e){
   e.preventDefault();
});

The .on() should be set up like this to work with dynamically created elements. Also, make sure to use Jquery version 1.8 or earlier versions.

Try:

$('#container').on("click",'.hello',function(e){
 e.preventDefault();
 });

It also work from this..

$('.hello').click(function(){
     e.preventDefault();
});

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