修改函数中的javascript变量
modifying javascript variable within function
我读过关于全局声明变量,然后能够在函数中修改它们的文章,但事情对我来说并不顺利。
这是我的代码:
var selectee = "JK";
// get state selected
$('select.form-control.bfh-states').change(function () {
selectee = $('select option:selected').val();
// works correctly, but i need to access it outside the function
console.log(selectee);
});
// output JK, should change based on a select box on the form
console.log(selectee);
这是因为只有当从select元素触发更改事件时,change()
处理程序才会被执行。您在顺序执行中使用console.log()
语句,该语句将在触发更改处理程序之前执行
//this is correct
var selectee = "JK";
//this registers a change handler for the select element
$('select.form-control.bfh-states').change(function () {
//but this will not execute now!!! it will get executed only when the select elements change event is fired
selectee = $(this).val();
console.log(selectee); // works correctly, but i need to access it outside the function
});
//this will get executed as soon as the change handler is registered not after the handler is executed
console.log(selectee);
如果您希望selectee
在select
元素中选择值,那么您可以执行类似的操作
var selectee = $('select.form-control.bfh-states').val() || "JK";
或者在处理程序像一样连接到dom就绪后手动启动选择更改处理程序
var selectee = "JK";
$('select.form-control.bfh-states').change(function () {
selectee = $(this).val();
console.log(selectee); // works correctly, but i need to access it outside the function
}).change();
解决此问题的方法是从更改处理程序中执行需要selectedee值的代码。首先不应该将其存储在全局变量中。
// get state selected
$('select.form-control.bfh-states').change(function () {
var selectee = $('select option:selected').val();
console.log(selectee); // works correctly, but i need to access it outside the function
// call your other code from here and pass it the current value of selectee
myOtherFunction(selectee);
});
为了解释,.change()
回调函数仅在select的值实际更改时执行。它将在稍后的某个时候被调用。因此,为了稍后使用selectedee的值,您需要在更改新值的同时执行需要该值的代码。
您的代码并不像您想象的那样是过程性的。selectee
将仅在激发选择控件的更改事件之后反映新值。事件处理程序中的代码在被调用/触发/激发之前不会执行。但是那些外部的,比如console.log(selectee)
,将在第一次加载代码时执行(在您的情况下,还没有调用更改事件)。
这是因为change
处理程序是一个回调,它将在事件发生后触发,而不是执行代码顺序
另一种方法是将选定的值传递到一个新函数中,从而在该函数中访问它(而不是全局访问)。试试这个:
selectee = "JK";
// get state selected
$('select.form-control.bfh-states').change(function () {
selectee = $('select option:selected').val();
// works correctly, but i need to access it outside the function
mynewfunc(selectee);
});
function mynewfunc(){
alert(selectee);
}
注意:一旦触发更改,就无法在新函数mynewfunc
之外访问变量selectee
。
演示
相关文章:
- 将函数的上下文应用于javascript变量
- 如何通过ajax刷新JSF填充的javascript变量
- Javascript变量赋值|
- 限制javascript变量的最小/最大整数
- 来自文本输入null的html javascript变量
- 访问jsrender模板中的全局javascript变量并更新它
- 从数据库中获取数据并插入JavaScript变量
- 如何将javascript变量传递到Meteor Spacebars模板中
- 将JavaScript变量保存到Rails模型
- 在if语句下的html中使用javascript变量
- Javascript变量分配-按类别
- 操作javascript变量[HTML]以只显示文本
- 无法比较javascript变量
- 如何将smarty变量与javascript变量进行比较
- 如何使用PHP将javascript变量添加到mysql数据库中
- Javascript 变量使用 jquery 查找变量
- 重新加载页面时Javascript变量发生变化
- 在asp classic中使用javascript变量
- 全局Javascript变量变为null
- 如何向服务器端提交javascript变量