如何在jquery中选择.click()内的变量这是代码:
$('#text-box').click(function(){
var type = $(this).val();
});
alert(type);// this will not get alerted
我如何提醒type
?我不希望它在被点击时收到警报
<input type='text' id='text-box'>
答案 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-box
是textbox
,那么您可能需要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,您可以管理变量变化..
这是一个简单的例子:
$(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);