jQuery:事件函数没有变量?

时间:2010-06-25 15:36:59

标签: jquery events

如果选择单选按钮,我想要显示或隐藏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在事件函数内是未知的。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您可以稍微更改它,以基于当前元素的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");
});

答案 1 :(得分:1)

好吧,你没有给我们任何背景信息,但很有可能,你在设置这些事件处理程序之后改变了companyVarID的值......

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

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

// ...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