Creé una función que reconoce en qué publicación se ha hecho clic.
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" class="recognize-post" data-id="<?php the_title() ?>">POST</button> El código anterior funciona perfectamente y reconoce la publicación correcta, pero necesito pasar clickedButton fuera de esta función y no sé cómo hacerlo.
Necesito tenerlo en la función else if , este es mi intento
else () { ... } else if (button-id === "recognize-post") { console.log(clickedButton) } Aquí viene el problema, clickedButton está subestimado y necesita que reconozca la publicación exactamente de la misma manera que en la función de clic. ¿Es posible?
Puede crear una función separada que incluya la información que desea conservar.
// 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 ... ... }) }) }Entonces, el problema aquí es que si declara una función variable en un " alcance " dado, en su caso, el alcance de la función anónima, solo se definirá dentro de ese alcance. Si desea utilizar la variable fuera de la función, debe declararla fuera de la función.
Entonces, por ejemplo, si su código fue
function foo() { var myVariable = 0; } foo(); // This will throw an error, cuz myVariable is not defined in this scope console.log(myVariable);podría solucionarlo declarando la variable fuera del alcance de la función
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!