如何使用jquery将onclick函数的值传递给全局范围?

时间:2018-05-26 13:36:43

标签: jquery

$('.button').on('click', function grab(){
    this.value
       //I need to use this value from outside of current function
})

console.log(grab());

如何将onclick函数的值传递给jquery的全局范围?我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您只需要在全局范围内声明一个变量......

var myVal;

$('.button').on('click', function(){
  myVal = this.value;
  console.log(myVal);
})

现在,myVal在点击按钮后会有正确的值。您可以使用代码中其他位置的另一个事件处理程序来测试它。例如:

$(".someOtherElement").on("click",function(){
  console.log(myVal);
}