jQuery 在jQuery中,$('body')可以选择body元素,而$('body')可以和$('some text')一样,那么如何区分呢?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3083575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In jQuery, $('body') can be selecting the body element, but $('body') can be just like $('some text'), so how to distinguish?
提问by nonopolarity
The reason is that we can do
原因是我们可以做到
$('<div>some text</div>').prependTo('#someDiv')
so, this is also ok to do:
所以,这也可以:
$('some text').prependTo('#someDiv')
but we can't change some text
to body
? body
is just as good as any text...
但我们不能更改some text
为body
? body
和任何文字一样好......
(the above code is adding some text
to the div with id someDiv
, so what if I want to add the word body
to the div?)
(上面的代码是将some text
id添加到 div 中someDiv
,那么如果我想将单词添加body
到 div 中呢?)
but $('body') becomes a selector for the body element... so is there a rule that says, we can use any text as HTML code, so long as it is not the name of HTML elements?
但是 $('body') 变成了 body 元素的选择器......所以有没有规则说,我们可以使用任何文本作为 HTML 代码,只要它不是 HTML 元素的名称?
采纳答案by Nick Craver
Basically this is never valid:
基本上这永远不会有效:
$('generic text here, *not* a selector or HTML');
That should alwaysbe either a selector (finding an element) or html (creating element(s)), you can view the API for $()
here.
这应该始终是选择器(查找元素)或 html(创建元素),您可以在$()
此处查看 API。
You want to use one of the other DOM Insertion methodshere, .prepend()
in this case:
您想在这里使用其他DOM 插入方法之一,.prepend()
在这种情况下:
$('#someDiv').prepend('any text or html here is valid, <b>Hey look bold</b>.');
回答by Sean Hogan
If it contains html tags then it is treated as html (except it strips text before the first tag and after the last). eg $("<div>some text</div>")
. Otherwise it is treated as a selector, eg $("some text")
.
如果它包含 html 标签,则将其视为 html(除了它在第一个标签之前和最后一个标签之后去除文本)。例如$("<div>some text</div>")
。否则,它将被视为选择器,例如$("some text")
.
回答by RoToRa
Dealing with text nodes isn't JQuery's strong suit. You could use normal DOM methods:
处理文本节点并不是 JQuery 的强项。您可以使用普通的 DOM 方法:
$('#someDiv')[0].appendChild(document.createTextNode("body"));
回答by Mario Menger
This is because jQuery considers selectors before creating HTML snippets. "body" is a valid selector and will be used as a selector.
这是因为 jQuery 在创建 HTML 片段之前会考虑选择器。“body”是一个有效的选择器,将用作选择器。
You'd be better of using the prepend function to prepend HTML or text to a node:
您最好使用 prepend 函数将 HTML 或文本添加到节点:
$('#someDiv').prepend('some text');
The value passed to prepend is not used a selector and you could add the text "body".
传递给 prepend 的值不用作选择器,您可以添加文本“body”。