(this) 前面的 $ 美元符号用于选择当前元素。我对选项前面的 $ 和 thisSelect 有点困惑。它们有什么特殊含义吗?
var $options = $(this).children('option');
var $thisSelect = $(this);
感谢您的帮助
最佳答案
正如大家所说,这只是一个约定。
我在变量前面使用 $
符号来标识该变量包含一个对象。
var thisIsANumber = 1024; // No $.. Its a normal variable
var $divElement = $('div#idOfDiv'); // Yes! Its a jQuery Object
var $this = $(this); // Commonly used to reduce the work javascript has to do!
//Now I can use something like this.. (Notice how easy it is to read!)
$divElement.slideUp();
// Or a more `real world` example!
$('#element').click(function(){
// Hold $(this) inside a variable
// So we don't have to traverse the dom unnecessarily
var $this = $(this); // Save it (its a object.. so prepend a `$` )
$this.hide(); // Use it again
$this.fadeIn(); // and again
// ^ Has a dollar sign, because it is a jQuery Object.
});
您将看到大量插件使用此约定(嗯..至少是写得好的插件)。
通过将对象存储在变量中,Javascript 不必每次都爬行代码来获取元素。相反,我们已经拥有该元素(在变量内),因此我们使用它来引用它。
如果在同一个回调函数中多次使用 $(this)
,则应将其存储在变量中。 (var $this = $(this);
)。否则,每次使用它时,javascript 都必须每次从源代码中获取元素(这会大大降低性能!(特别是对于在慢速/旧计算机上浏览的人来说!)。
关于jquery - 变量前面的$是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14362939/