在JQuery中的.click()事件中选择一个变量

时间:2014-07-17 07:07:43

标签: javascript jquery

如何在jquery中选择.click()内的变量这是代码:

    $('#text-box').click(function(){
       var type = $(this).val();
    }); 
     alert(type);// this will not get alerted 

我如何提醒type?我不希望它在被点击时收到警报

<input type='text' id='text-box'>

5 个答案:

答案 0 :(得分:4)

在处理程序之外定义它以在其他函数中将其放在处理程序的一侧。您在处理程序外警告它的方式将提醒最初分配的值,但不会在click处理程序中分配时。

var type = "0";
$('#text-box').click(function(){
   type = $(this).val();
}); 
alert(type);// Now this will get alerted but before click with initial value i.e. 0

如果#text-boxtextbox,那么您可能需要change / keyup个事件而不是点击。

要在单击类型变量后查看存储的值,您可以添加一个按钮并将click事件绑定到它以查看类型变量中的内容。确保在单击按钮

之前触发#text-box事件
$('#someButtonId').click(function(){
    alert(type);
});

答案 1 :(得分:0)

应该这样做 - 首先定义类型变量,使变量范围超出函数范围,以便您可以在click()函数

之外访问它
var type =0;
$('#text-box').click(function(){
 type = $(this).val();
}); 
 alert(type);

答案 2 :(得分:0)

请注意,您必须将所有代码放在doc ready处理程序中:

$(function(){
   var type = ''; // declare outside of event here
   $('#text-box').click(function(){
      type = $(this).val(); // update the value in the var type here
   }).trigger('click'); // <----this triggers the click on load to update the val
   alert(type);// now this will get alerted 
});

答案 3 :(得分:0)

使用Watch.JS,您可以管理变量变化..

这是一个简单的例子:

http://jsfiddle.net/4QLUu/

$(document).ready(function(){

  var watched = {value:0};
  watch(watched,"value", function(){
    console.log(watched.value);
 });

 $('#text-box').on("change",function(){
     console.log($(this).val());
   watched.value = $(this).val();
 }); 
});

答案 4 :(得分:0)

如果要求您不能在此函数之外定义此变量,那么首先要检查上面的代码,有两种方法可以执行此操作,那么您应该使用会话对象(Web存储)。

  $('#text-box').click(function(){
        sessionStorage.setItem(key,$(this).val());
    });
        var item = sessionStorage.getItem(key);
        alert(key);