jQuery:事件函数不接受变量?

jQuery:事件函数不接受变量?,jquery,events,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("

如果选择了单选按钮,我希望显示或隐藏一个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");
    });

它应该可以工作(我警告测试了事件是否实际运行),但我认为由于某种原因,变量
companyvard
在事件函数中是未知的。如何修复此问题?

您可以根据当前元素的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");
});

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

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

,是相当干净的,但这里有一个替代技术,只是为了让你了解发生了什么

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

老实说,我更喜欢你的方式(更干净)