简体   繁体   中英

jQuery click doesn't work

I have a problem with nested divs, and jQuery's click function. Clicking on .header-fb, .header-twitter or .header-linkedin don't give any results. No errors in console. I'm not sure what's going on. These classes have background image, not sure, if that makes problem too. Here's the code:

<div>
 <div id="header-social" class="four columns mobile-two">
 <div class="header-fb"><a href="http://www.facebook.com" >&nbsp</a></div>
 <div class="header-twitter"><a  href="https://twitter.com" >&nbsp</a></div>
 <div class="header-linkedin"><a  href="http://www.linkedin.com/">&nbsp</a></div>
</div>

and javascript:

 <script type="text/javascript">
        jQuery(document).ready(function() {
            jQuery(".header-fb").click(function(){
                  window.location=jQuery(this).find("a").attr("href");
                  return false;
            });
            jQuery(".header-twitter").click(function(){
                window.location=jQuery(this).find("a").attr("href");
                return false;
            });
            jQuery(function() {
                jQuery('.header-linkedin').click(function(){
                    window.location=jQuery(this).find("a").attr("href");
                    return false;
                });
            });
        });
    </script>

What about if you try:

$(function() {

   $(".header-fb").click(function(){
      window.location = $(this).find("a").attr("href");
   });

   $(".header-twitter").click(function(){
      window.location= $(this).find("a").attr("href");
   });

   $('.header-linkedin').click(function(){
      window.location = $(this).find("a").attr("href");
   });

});

You're adding an extra jQuery method at the bottom of your code (for some reason) and using a lot of long-hand syntax. You also do not need to return false .

IF your HTML should look like this:

<div id="header-social" class="four columns mobile-two">
   <div class="header-fb"><a href="http://www.facebook.com" >&nbsp</a></div>
   <div class="header-twitter"><a  href="https://twitter.com" >&nbsp</a></div>
   <div class="header-linkedin"><a  href="http://www.linkedin.com/">&nbsp</a></div>
</div>

Than you can try with:

(function( $ ){  // remap $ to jQuery
  $(function(){  // DOM ready shorthand

    $('#header-social').on('click','div',function(){

       var goTo = $(this).find('a').attr('href');
       window.location = goTo ;

    });

  });
})( jQuery );

http://jsbin.com/uxowoj/1/edit

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