gpt4 book ai didi

javascript - jquery $ ('
' ) vs $ ('
' )

转载 作者:行者123 更新时间:2023-12-03 21:51:40 26 4
gpt4 key购买 nike

Possible Duplicate:
$('<element>') vs $('<element />') in jQuery

这两种方法中哪一种是正确的方法:

$('<div>') 

$('<div />')

它们似乎都有效。一种方法比另一种方法更正确,或者它们总是有效吗?

最佳答案

来自 docs :

If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it has <tag ... > somewhere within the string). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements. You can perform any of the usual jQuery methods on this object:

$('<p id="test">My <em>new</em> text</p>').appendTo('body'); 

If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's innerHTML mechanism. In most cases, jQuery creates a new element and sets the innerHTML property of the element to the HTML snippet that was passed in. When the parameter has a single tag, such as $('<img />') or $('<a></a>'), jQuery creates the element using the native JavaScript createElement() function.

为了确保跨平台兼容性,代码段必须格式正确。可以包含其他元素的标签应与结束标签配对:

$('<a href="http://jquery.com"></a>');

或者,jQuery 允许类似 XML 的标记语法(斜杠之前有或没有空格):

$('<a/>');

不能包含元素的标签可能会快速关闭,也可能不会:

$('<img />');
$('<input>');

关于javascript - jquery $ ('<div>' ) vs $ ('<div/>' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10402567/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com