简体   繁体   中英

unable to trigger click event using jQuery .trigger

I am having some trouble in triggering a click event .

I have html something like this :

<div class="carousel-control" >
<a href='#' id="carousel_1">1</a>
<a href='#' id="carousel_2">2</a>
<a href='#' id="carousel_3">3</a>
<a href='#' id="carousel_4">4</a>
<a href='#' id="carousel_5">5</a> 
etc
</div>

Now Here is the JS

jQuery('.carousel-control a').bind('click', function() {
        alert("carousel cliced")
        return false;
      });

$('#nextimg').click(function() {

var car_index=2;
                $('#carousel_'+(car_index+1)).trigger('click');
alert("next image clicked");
               return false;
            });

Now when I manually click the href tag the alert("carousel clicked") appers, but when I click the nextimg only next image alert appears not the carousel alert.

I tried using

 $('#carousel_2').trigger('click'); 
 $('#carousel_2').click();
 $('#carousel_2').triggerHandler('click');

There seems to be no error in the firebug too.

Can someone please help me out. :) Thank you,

I'm not certain... but any chance it has to do with your spelling of index in var car_inedx=2; ? (I make mistakes like this often enough myself.)

Keep the click event under "Document Ready event".

Here it goes like this :

jQuery(document).ready( function() {
      jQuery('.carousel-control a').bind('click', function() {
         alert("carousel cliced")
         return false;
       });

       $('#nextimg').click(function() {
             var car_index=2;
             $('#carousel_'+(car_index+1)).trigger('click');
             alert("next image clicked");
             return false;
       });
});

Try

$('#carousel_'+(car_index+1)).click();

instead of

$('#carousel_'+(car_index+1)).trigger('click');

You have a typo in var car_inedx .

Working demo: http://jsfiddle.net/rBFxu/

using

 $('.carousel-control a').bind('click', function()

instead of this

jQuery('.carousel-control a').bind('click', function()

Works well.

But can anyone explain me why is it happening so ?

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