如何在jQuery的change事件函数外部获取更新后的变量值?
如何在change事件触发后在函数外部获取更新后的变量值
我有一个包含.on('change', function(){})的函数,在change事件回调前定义了变量。当点击按钮触发change事件时,回调内的变量会更新,但在回调外部访问该变量会提示“未定义”错误。怎么在事件触发后,在函数外部拿到变量的新值?
相关代码示例:
/* Ready Function */ $(function(){ $('.container').each(function(){ let date = new Form($(this)); }); }); const Form = function(this$obj){ this.$obj = this$obj; this.init(); }; Form.prototype.init = function init(){ this.checkFunction(); this.clickFunction(); }; Form.prototype.checkFunction = function checkFunction(){ let formField = this.$obj.find('.input_field_01'); let today = '01 / 28 / 1979'; formField.on('change', function(){ if (formField != ''){ console.log('date found'); newValue = formField.val(); console.log(newValue); }else { console.log('no date found'); newValue = mm + '/' + dd + '/' + yyyy; console.log(newValue); } console.log('outside if statement'); console.log(newValue); }); console.log('date outside change function'); // this is where things break newValue not defined if uncommented //today = newValue; console.log(today); } // working Form.prototype.clickFunction = function clickFunction(){ let findField = this.$obj.find('.input_field_01'); let button = this.$obj.find('.date_updater'); let text = '02 / 19 / 1981' button.on('click',function(){ findField.val(text).change(); }); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <form> <input type="hidden" class="input_field_01" name="input_field_01" value=""> <span class="input_value_01"></span> </form> <br> <button class="date_updater" type="button"> Change Date </button> </div>
问题原因
- 异步执行顺序:
checkFunction是同步执行的,其中的console.log(today)会在change事件触发前就运行,此时newValue还没被赋值,自然会报错。 - 作用域与变量声明:
newValue没有用let/const/var声明,会自动成为全局变量,但即使声明了,它的作用域也局限在change回调或checkFunction内部,外部无法直接访问。 - 逻辑错误:原代码中
if (formField != '')是无效判断,应该检查formField.val()是否为空,而非DOM元素本身。
解决方案
方案一:将变量挂载到Form实例上
把需要共享的变量作为Form类的实例属性,这样实例内部的所有方法,以及外部通过实例对象,都能访问到最新值。
修改后的代码:
/* Ready Function */ // 存储实例,方便外部后续访问 let formInstances = []; $(function(){ $('.container').each(function(){ let dateForm = new Form($(this)); formInstances.push(dateForm); }); }); const Form = function(this$obj){ this.$obj = this$obj; this.today = '01 / 28 / 1979'; // 把变量挂载到实例上 this.init(); }; Form.prototype.init = function init(){ this.checkFunction(); this.clickFunction(); }; Form.prototype.checkFunction = function checkFunction(){ let formField = this.$obj.find('.input_field_01'); // 用箭头函数保留this指向当前Form实例 formField.on('change', () => { let newValue; // 修正判断逻辑:检查input的value if (formField.val() !== ''){ console.log('date found'); newValue = formField.val(); console.log(newValue); }else { console.log('no date found'); // 补全原代码未定义的日期变量逻辑 const now = new Date(); const mm = String(now.getMonth()+1).padStart(2, '0'); const dd = String(now.getDate()).padStart(2, '0'); const yyyy = now.getFullYear(); newValue = `${mm} / ${dd} / ${yyyy}`; console.log(newValue); } console.log('outside if statement'); console.log(newValue); // 更新实例上的today属性 this.today = newValue; }); console.log('date outside change function'); console.log(this.today); // 输出初始值 } // working Form.prototype.clickFunction = function clickFunction(){ let findField = this.$obj.find('.input_field_01'); let button = this.$obj.find('.date_updater'); let text = '02 / 19 / 1981' button.on('click',function(){ findField.val(text).change(); }); } // 外部获取示例:比如在某个时机获取第一个实例的最新日期 // setTimeout(() => { // console.log('外部获取到的最新日期:', formInstances[0].today); // }, 3000);
方案二:直接从DOM元素读取最新值
因为你的变量值本质对应input的value,外部需要时直接查询DOM元素的value即可,无需额外维护变量:
// 定义获取最新日期的函数 function getLatestDate() { // 取input的值,为空则用默认值 return $('.container .input_field_01').val() || '01 / 28 / 1979'; } // 示例:在需要的地方调用 // console.log(getLatestDate());
方案三:通过自定义事件通知外部
当change事件触发并更新值后,触发一个自定义事件,外部监听该事件来获取新值,适合需要实时响应的场景:
Form.prototype.checkFunction = function checkFunction(){ let formField = this.$obj.find('.input_field_01'); formField.on('change', () => { let newValue; if (formField.val() !== ''){ console.log('date found'); newValue = formField.val(); }else { console.log('no date found'); const now = new Date(); const mm = String(now.getMonth()+1).padStart(2, '0'); const dd = String(now.getDate()).padStart(2, '0'); const yyyy = now.getFullYear(); newValue = `${mm} / ${dd} / ${yyyy}`; } // 触发自定义事件,携带新值作为参数 $(document).trigger('dateUpdated', [newValue]); }); } // 外部监听自定义事件,获取新值 $(document).on('dateUpdated', function(e, newValue) { console.log('外部收到新日期:', newValue); // 可以在这里更新页面显示,比如更新span的文本 $('.input_value_01').text(newValue); });
内容的提问来源于stack exchange,提问作者DigitalDesigner
相关产品推荐
相关产品推荐

