如何在 jquery 中选择 .click() 内的变量,这是代码:
$('#text-box').click(function(){
var type = $(this).val();
});
alert(type);// this will not get alerted
我如何提醒类型
?我不希望它在被点击时收到警报
<input type='text' id='text-box'>
最佳答案
在处理程序之外定义它,以将其从其他函数中的处理程序中取出。您在处理程序外部提醒它的方式将提醒最初分配的值,但不会在 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
事件而不是点击。
要在单击类型变量后查看存储的值,您可以添加一个按钮并将单击事件绑定(bind)到它以查看类型变量中的内容。确保在单击按钮之前触发 #text-box
事件
$('#someButtonId').click(function(){
alert(type);
});
关于javascript - 在 JQuery 的 .click() 事件中选择一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24796992/