简体   繁体   English

从onchange事件处理程序中提取变量以用于其他功能

[英]Extracting variable from onchange event handler for use in other functions

I have an event handler listening for a change in a dropdown and setting the value of a variable. 我有一个事件处理程序,侦听下拉列表中的更改并设置变量的值。 I have declared the variable as global ie outside of any functions, and then set the value on change. 我已经将变量声明为全局变量,即在任何函数之外,然后在更改时设置值。 However, once it has changed I need to be able to pick up the variable in other functions (not within the even handler). 但是,一旦更改,我就需要能够在其他函数中(而不是在偶数处理程序中)拾取该变量。 How can i 'extract' it from within the event handler? 我如何从事件处理程序中“提取”它? I've tried to return it but no luck - here is the code: 我试图将其退回,但没有运气-这是代码:

$(document).on('change', 'select#search_subject', function () {
    if ($('#sBar3').show()) {
        $('#sBar3').hide();
    }
    var subject = $('#search_subject>option:selected').text();
    var id = $('#search_subject>option:selected').val();
    ajaxSubject(subject, '#sBar3');
    return subject;
});
console.log(subject);   

the log just shows 'empty string' and I'm baffled. 日志仅显示“空字符串”,我感到困惑。 If possible I dont want to rejig the code to include everything within the event handler (there's lots of Google Map generating code in there and it will make for a pain) - i just need to get the subject variable out of the event handler if that makes sense - Thanks 如果可能的话,我不想更改代码以将事件处理程序中的所有内容都包含进去(那里有很多Google Map生成代码,这会很麻烦)-我只需要从事件处理程序中获取subject变量即可很有道理-谢谢

By using the var keyword, you're creating a new local variable, which you're then assigning the subject text to. 通过使用var关键字,您可以创建一个新的局部变量,然后将其分配给主题文本。 If you've already defined subject in the global scope, then your assignment line should simply be: 如果您已经在全局范围内定义了subject ,那么您的任务行应该简单地是:

subject = $('#search_subject>option:selected').text();

If the select is not created later, then this would be simpler code after you remove the var that makes subject local 如果选择不是稍后创建的,那么在删除使主题成为本地的var之后,这将是更简单的代码

$("#search_subject").on('change',function () {
  $('#sBar3').toggle();
  subject = $('option:selected',this).text();
  var id = $(this).val(); // not used?
  ajaxSubject(subject, '#sBar3');
  window.console && console.log(subject);   
  return subject;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM