【问题标题】:jQuery: Event function not taking variable?jQuery:事件函数不带变量?
【发布时间】:2010-06-25 15:36:59
【问题描述】:

如果选择了单选按钮,我希望 div 显示或隐藏。这是代码:

    // add event to hide unimportant details when var is disabled and show when enabled
    $('#companyVar' + companyVarID + 'Enabled').change(function() {
        $('#companyVar' + companyVarID + 'Unimportant').fadeIn("slow");
    });
    $('#companyVar' + companyVarID + 'Disabled').change(function() {
        $('#companyVar' + companyVarID + 'Unimportant').slideUp("slow");
    });

它应该可以工作(我提醒测试事件实际运行),但我认为由于某种原因,变量companyVarID 在事件函数中是未知的。我该如何解决这个问题?

【问题讨论】:

    标签: jquery events


    【解决方案1】:

    好吧,您没有费心给我们提供任何上下文,但很有可能,您在设置这些事件处理程序后更改了 companyVarID 的值...

    不知何故,您需要保留该值(而不仅仅是对变量的引用,它已被闭包充分捕获)。

    Nick's solution will work, and 相当干净,但这里有一种替代技术,只是为了让您了解正在发生的事情......

    // ...something assigns a value to companyVarID
    
    // put event-handler wireup in an anonymous function (to be called immediately)
    // mask the outer variable with a parameter that can't be changed externally
    (function(companyVarID) 
    {
      // add event to hide unimportant details when var is disabled and show when enabled
      $('#companyVar' + companyVarID + 'Enabled').change(function() {
        $('#companyVar' + companyVarID + 'Unimportant').fadeIn("slow");
      });
      $('#companyVar' + companyVarID + 'Disabled').change(function() {
        $('#companyVar' + companyVarID + 'Unimportant').slideUp("slow");
      });
    
     // pass the value of the outer variable to our anonymous function, allowing 
     // it to be captured in the event-handler closures
    })(companyVarID);
    
    // ...something changes the value of companyVarID
    

    【讨论】:

    • 老实说,我更喜欢你的方式 =) 更干净
    【解决方案2】:

    您可以根据当前元素的 ID 稍微更改它,如下所示:

    $('#companyVar' + companyVarID + 'Enabled').change(function() {
        $('#' + this.id.replace('Enabled', 'Unimportant')).fadeIn("slow");
    });
    $('#companyVar' + companyVarID + 'Disabled').change(function() {
        $('#' + this.id.replace('Disabled', 'Unimportant')).slideUp("slow");
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多