English 中文(简体)
创建空元素, 开始标签对自我关闭标签
原标题:Creating an empty element with start tag vs. self closing tag
  • 时间:2012-05-25 15:46:19
  •  标签:
  • jquery

在jQuery中,这两者之间是否有任何区别:

$( <div> ).appendTo( body );

还有这个:

$( <div /> ).appendTo( body );

我总是看到它“自我接近”的方式,但我发现第一个方法被某些生产代码使用时没有错误。 任何可能性都会引发问题,或者这是可以接受的做法吗?

最佳回答

http://api.jquery.com/jQuery/#jQuery2" rel=“noreferrer”>文件写道:

When the parameter has a single tag, such as $( <img /> ) or $( <a></a> ), jQuery creates the element using the native JavaScript createElement() function.

它还说:

无法包含元素的标记可能是快速关闭或不关闭的标记

因此,窗体 $( & lt; div>) 明显也有效,但它没有记录。 从文档中可以清楚地看出,要使用关闭标签的标签,该标签要么有关闭标签,要么是自封标签。

我将坚持有文件记录的文本,因为在未来版本中,它不太可能成为破碎变化的受害者。

<rant>
The jQuery library have a habit of putting as much as possible in a single function call (see the recent on addition for an example), so it s not so far fetched that they would invent something new to happen when you use a non-self-closing tag...
</rant>

问题回答

既不是 $(“ & lt; div> ”) 也不是 $(“ & lt; div / & gt; ”) 会引起问题 。

证明是这样的:如果我们去jQuery 源 ,我们可以看到,如果选择者使用单标签语法 lt;... & gt; ,它会用这个正则表达式来分析选择者:

rsingleTag = /^<(w+)s*/?>(?:</1>)?$/

只有符号部分用于 createEcent 元素 和关闭斜线可任选 。

只要无事可做,这种语法就不会造成问题。

$("<div>") // Ok!
$("<div>foobar") // Not Ok!
$("<div><p>") // Not Ok!

查询请见http://api.jquery.com/jQuery/#jQuery2





相关问题
getGridParam is not a function

The HTML: <a href="javascript:void(0)" id="m1">Get Selected id s</a> The Function: jQuery("#m1").click( function() { var s; s = jQuery("#list4").getGridParam( selarrrow )...

selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

jQuery cycle page with links

I am using the cycle plugin with pager functionality like this : $j( #homebox ) .cycle({ fx: fade , speed: fast , timeout: 9000, pager: #home-thumbs , ...

jquery ui dialog opens only once

I have a button that opens a dialog when clicked. The dialog displays a div that was hidden After I close the dialog by clicking the X icon, the dialog can t be opened again.

jConfirm with this existing code

I need help to use jConfirm with this existing code (php & Jquery & jAlert). function logout() { if (confirm("Do you really want to logout?")) window.location.href = "logout.php"; } ...

Wrap text after particular symbol with jQuery

What I m trying to do, is wrap text into div inside ll tag. It wouldn t be a problem, but I need to wrap text that appears particularly after "-" (minus) including "minus" itself. This is my html: &...

热门标签