将参数括在引号中的 JQuery 规则是什么?为什么 $(文档) 和 $('document') 都可以,但只允许 $(this)?



在jQuery中,我可以写$(document)$('document')/$("document"),但只允许$(this)(我不能用任何引号括this)。此外,任何选择器都应引用:($("div")是可以的,而$(div)不是)。

我不明白到底该怎么做

  • 始终被引用
  • 可选报价
  • 永远不要被引用

例如,thisdocument似乎都是(特殊)关键字(不是选择器),但对它们有不同的规则是令人困惑的。另外,我想任何jQuery选择器都应该被引用。

<script>
$(document).ready(function(){  <!-- $('document') is also valid -->
$('p').click(function(){
$(this).hide();            <!-- $('this') is invalid -->
$("div").hide();
});     
});    
</script>

jQuery函数($())可以接受几种类型的参数,包括(但不限于):

  1. 一个 DOM 元素(对象 - 不是字符串)
  2. 选择器(字符串)

当您有一个引用 DOM 元素的变量/属性时,您可以使用第一种语法。

在第二个语法中,jQuery将应用选择器来查找匹配的DOM元素。这意味着字符串必须遵循CSS语法(带有一些jQuery扩展)。

两者是完全不同的。

$('document')不选择任何内容

$('document')选择任何东西是一种误解。它遵循第二种语法,但"document"不是返回任何内容的选择器,因为<document>不是元素(除非您专门添加了元素)。

您可以在此处看到它不选择任何内容:

console.log($("document").length); // 0
console.log($(document).length); // 1
// Now add a <document>:
var doc = document.createElement('document');
document.body.appendChild(doc);
// ... and it works
console.log($("document").length); // 1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

jQuery的.ready()方法

你提到$('document').ready()有效 - 这可能是你问题的更深层次的原因 - 但那是因为选择器与ready工作无关。引自jQuery文档:

jQuery提供了几种方法来附加一个函数,该函数将在 DOM 已准备就绪。以下所有语法都是等效的:

$( handler )
$( document ).ready( handler )
$( "document" ).ready( handler )
$( "img" ).ready( handler )
$().ready( handler )

你选择什么并不重要。即使$('abcdef').ready也会起作用。

this

jQuery 在其许多方法中调用回调函数时,this设置相关的 DOM 元素。这使得this成为传递给$的候选值(第一个语法)。$(div)将不起作用,因为div不是变量,除非您声明它:

$("div").each(function () {
console.log($(this).text()); // "hello"
// Does not work:
console.log($(div).text()); // ""
var div = this;
// Now it works:
console.log($(div).text()); // "hello"
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>hello</div>

在你的例子中:$(this).hide();this是一个 JavaScript 变量,表示被点击的"P",触发事件。

JavaScript 变量从不被引用。

DOM 元素选择器总是被引号(文档和窗口是"特殊情况")。

要引用 DOM 上的任何元素,必须用引号将其括起来。例如: 如果你有如下所示的 HTML:

<button>Click my button</button>

你的jQuery可能看起来像这样:

$(document).ready(function({
// listen for hover on the button
$('button').mouseenter(function() { ... });  // 'button' is a selector for <button>, use quotations
...
// assign the button to a variable and perform an action
var buttonVar = 'button';  
$(buttonVar).mouseenter(function(){ ... }); // buttonVar is a variable, do not use quotations
});

$(this)的情况下,this是一个表示当前活动元素的变量。 就个人而言,我在循环浏览一系列相同类型的元素或通过数组的元素时使用$(this)

例如,您的 HTML 可能如下所示:

<p class="highlight">Highlight me</p>
<p class="nohighlight">Do not highlight me</p>
<p class="highlight">Highlight me</p>

你的jQuery可能看起来像这样:

$('.highlight').each(function(){         // 'highlight' is a selector for class="highlight", use quotations
$(this).css("background","yellow");   // this is a variable, do not use quotes
});

相关内容

最新更新