Home > Mobile >  Passing variable that detects specific button in jQuery
Passing variable that detects specific button in jQuery

Time:02-19

I created function that recognize which post has been clicked on.

jQuery(document).ready(function() {
       jQuery(.recognize-post).on("click", function() {
              var clickedButton = jQuery(this).data("id")
              console.log("click button with post id: ", clickedButton)
              button-id = "recognize-post"
    ...
    ...
})
})
}

html

<button id="recognize-post"  data-id="<?php the_title() ?>">POST</button>

Code above works perfectly and in recognizes the correct post, but I need to pass clickedButton outside of this function and I don't know how to do so.

I need to have it in else if function, this is my attempt

else () {
...
} else if (button-id === "recognize-post") {
console.log(clickedButton)
}

Here the problem comes, clickedButton is underfined and need it to recognize post in exactly the same way how in on click function. Is it possible?

CodePudding user response:

You can make a separate function that takes in the information you want to preserve.

// make a new function
function doSomethingWithTheIdAndBtn(id, btn) {
 // take in arguments that represent the id or btn or whatever you need
    else () {
    ...
    } else if (id === "recognize-post") {
    console.log(btn)
}

}

jQuery(document).ready(function() {
       jQuery(.recognize-post).on("click", function() {
              var clickedButton = jQuery(this).data("id")
              console.log("click button with post id: ", clickedButton)
              button-id = "recognize-post"
              doSomethingWithTheIdAndBtn(button-id, clickedBtn) // call the function
    ...
    ...
})
})
}

CodePudding user response:

So, the issue here is that if you declare a variable function in a given "scope" — in your case, the anonymous function's scope — it will only be defined inside of that scope. If you want to use the variable outside of the function, you need to declare it outside of the function.

So, for instance, if your code was

function foo() {
    var myVariable = 0;
}
foo();
// This will throw an error, cuz myVariable is not defined in this scope
console.log(myVariable); 

you could fix it by declaring the variable outside of the function's scope

var myVariable; // declare it outside of the function

function foo() {
    myVariable = 0; // give it a value inside of the function
}
foo(); // call foo so that myVariable has a value

console.log(myVariable); // this will print 0. Success!
  • Related