简体   繁体   中英

how to bind a click event to an element in another click element

The second click event that is binded to $("play") does not execute. How can i bind another click event under a click event? I cant get the data newNumber if i write the second click event outside the first click event.

This piece of code is in the slide() function.

var that = this;
$("#stop").click(function(){
    clearInterval(set);
    var newNumber = [num, numb, list]; //the value needed by click event that is binded to "play"

    $("play").click(newNumber, function() {
        num = newNumber[0];
        numb = newNumber[1];
        list = newNumber[2];
        that.slide(image, num, list, numb);
    });
});

You're probably confusing two important terms: binding and triggering . You probably want to trigger the second event within the handler of the first, but you want to bind both to begin with anyway. Otherwise, you run into issues of binding the second event multiple times but never really triggering it.

You normally want to bind an event once at the start, but you can trigger it as many times as you need.

var that = this;
var newNumber;
$("#stop").click(function(){
    clearInterval(set);
    newNumber = [num, numb, list]; //the value needed by click event that is binded to "play"
    $("#play").click(); // trigger the second <=======
});
$("#play").click(function() {
    num = newNumber[0];
    numb = newNumber[1];
    list = newNumber[2];
    that.slide(image, num, list, numb);
});

But the question I would ask is, What Does 'this' refer to?

Use this - the right way is to trigger :

var that = this;
var newNumber = [];
$("#stop").click(function(){
    clearInterval(set);
    newNumber = [num, numb, list]; //the value needed by click event that is binded to "play"

   $("play").click() //or $("play").trigger('click')
});

$("play").click(function() {
        num = newNumber[0];
        numb = newNumber[1];
        list = newNumber[2];
        that.slide(image, num, list, numb);
});

  • Use .trigger() to bind a click event explicitly.
  • Define the array newNumber in global scope , to use it in other events.

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