为什么Docs不能接受jQuery.html()成功接受jQuery对象? [英] Why does jQuery.html() successfully accepts a jQuery object even though the docs says it can't?
问题描述
我只是想确切地了解它是如何工作的,因为我的代码中存在一个错误,可能与我的误解有关.
I am just trying to understand exactly how this works because I have a bug in my code that might be related to my misunderstanding.
文档说,.html(htmlString)
的htmlString
参数可以是htmlString
或function
,但是如果我这样做
The docs say the htmlString
parameter of .html(htmlString)
can be either an htmlString
or a function
, yet if I do this
var $div = $("div").detach();
$("body").html($div);
即使$div
是jQuery对象,分离的div correctly
仍会替换正文内容.
the detached div correctly
replaces the body contents even though $div
is a jQuery object.
为了完整起见,我的完整代码如下
For completeness' sake my full code is below
<html>
<body style="font-size:25px">
<div><p> CLICK TO TEST </p></div>
<script src="/js/jquery-1.11.1.min.js"></script>
<script>
$(function() {
$("p").click(function() { console.log("P1 CLICKED!"); });
var $div = $("div").detach();
$("body").html($div);
//$("body").html($div);
});
</script>
</body>
</html>
谢谢!
推荐答案
正如我在评论中所说,由于我们不是撰写文档的人,因此我们无法回答您的直接问题,但我可以向您展示原因工作.
As I said in the comment, we can't answer your direct question since we aren't the one writing the doc, but I can show you why it work.
您可以在此行中看到,jQuery检查如果传递的值是一个字符串.如果是,它将进行一些替换以生成有效的HTML,然后 c6>关闭.
As you can see on this line, jQuery check if the passed value is a string. If it is, it does some replace to make a valid HTML then, the if
close.
因此,无论您作为参数传递什么,它都会运行这些行:
So no matter what you pass as argument, it run those lines :
if ( elem ) {
this.empty().append( value );
}
如您所知,.append()
接受字符串,DOM元素或jQuery对象.因此,这就是它起作用的原因. .html
不会真的检查参数是否为字符串.
As you know, .append()
accept a string, DOM element or jQuery object. Hence, that is why it is working. .html
doesnt really check if the argument is a string.
这篇关于为什么Docs不能接受jQuery.html()成功接受jQuery对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!