Jquery这两行有什么区别? [元素选择]
What is the difference between these 2 lines of Jquery? [Element Selection]
我的 jquery 代码目前看起来像这样,使用元素 ID 选择器并将值设置为空字符串。
$("#theAddress").val("");
但是我看到它像下面的例子一样完成,我正在努力理解下面和我的行之间的区别,为什么你会像下面这样写,有什么好处吗?
$("textarea[name=theAddress]").val("");
谢谢
$("#theAddress")
selects 具有 id 的 theAddress 的 DOM 元素,例如<div id='theAddress'>..</div>
$("textarea[name=theAddress]")
selects 一个 DOM 元素,它是 textarea
但特定的 name 属性设置为 theAddress 例如<textarea name='theAddress'>...</textarea>
.
在这两种情况下,您都将 value
设置为空字符串。
如果你有这个元素,这可以想象 select 相同的节点:
<textarea id='theAddress' name='theAddress'>...</textarea>
这两种方式在现实世界中都没有任何好处 - 这完全取决于您想要什么 select。 #theAddress
方法可能会稍微快一些,并且应该是唯一的(例如 0 或 1 个结果),因为 ID 应该是唯一的。
我的 jquery 代码目前看起来像这样,使用元素 ID 选择器并将值设置为空字符串。
$("#theAddress").val("");
但是我看到它像下面的例子一样完成,我正在努力理解下面和我的行之间的区别,为什么你会像下面这样写,有什么好处吗?
$("textarea[name=theAddress]").val("");
谢谢
$("#theAddress")
selects 具有 id 的 theAddress 的 DOM 元素,例如<div id='theAddress'>..</div>
$("textarea[name=theAddress]")
selects 一个 DOM 元素,它是 textarea
但特定的 name 属性设置为 theAddress 例如<textarea name='theAddress'>...</textarea>
.
在这两种情况下,您都将 value
设置为空字符串。
如果你有这个元素,这可以想象 select 相同的节点:
<textarea id='theAddress' name='theAddress'>...</textarea>
这两种方式在现实世界中都没有任何好处 - 这完全取决于您想要什么 select。 #theAddress
方法可能会稍微快一些,并且应该是唯一的(例如 0 或 1 个结果),因为 ID 应该是唯一的。