jQuery的:当创建一个新的元素,我是否需要结束标记? [英] jQuery: When creating a new element, do I need the ending tag?

查看:178
本文介绍了jQuery的:当创建一个新的元素,我是否需要结束标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 变量$ DIV = $('< D​​IV CLASS =错误>')。appendTo($('#头'));

在创建新的元素,并将它们添加到DOM,你需要结束标记?为什么或者为什么不?如果我把内容放到我创建的标签我只需要结束标记?像这样:

 变量$ DIV = $('< D​​IV CLASS =错误>错误,哥们<!/ DIV>')。appendTo($('#头') );

我也可以创建一个有内容的元素,但离开了结束标记?好?坏了?

 变量$ DIV = $('< D​​IV CLASS =错误>')。appendTo($('#头'));


解决方案

虽然它可能工作,如果你不使用结束标签(或至少自我关闭标记)的你应该添加结束标记(自闭)(如前所述,为的跨平台兼容性的):


  

要确保跨平台的兼容性,必须很好地形成的片段。它可以包含其他元素的标签应关闭标签配对:

  $('< A HREF =htt​​p://jquery.com>< / A>');


  
  

另外,jQuery的允许类似XML的标记语法(带或不带斜杠前有一个空格):

  $('< A />');

这不能包含的元素可能是标签快速关闭或不:

  $('< IMG />');
$('<输入>');


这是jQuery的是如何创建的元素:


  

如果在HTML比没有属性一个标记更加复杂,因为它是在上述的例子中,元件的实际创建由浏览器的的innerHTML 机制来处理。在大多数情况下,jQuery的创建一个新的元素,并将元素中传递的HTML代码段的的innerHTML 属性。当参数有一个标签,比如 $('< IMG />') $('< A>< / A>'),jQuery的创建一个使用本地JavaScript元素的createElement()功能。



顺便说一句。您也可以通过数据作为第二个参数:

  $('< D​​IV />',{'类':'错误!-哥们':'错误',文字})

var $div = $('<div class="error">').appendTo($('#header'));

When creating new elements and adding them to the DOM, do you need the ending tag? why or why not? Do I only need the ending tag if i'm placing content into the tag i'm creating? like so:

var $div = $('<div class="error"> Error-Homie! </div>').appendTo($('#header'));

or could I create an element with content in it, but leave out the ending tag? Good? Bad?

var $div = $('<div class="error">').appendTo($('#header'));

解决方案

Although it may work if you don't use a closing tag (or at least self close the tag), you should add a closing tag (self-close) (as mentioned, for cross-platform compatibility):

To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag:

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

Alternatively, jQuery allows XML-like tag syntax (with or without a space before the slash):

$('<a/>');

Tags that cannot contain elements may be quick-closed or not:

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

This is how jQuery creates the elements:

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.


Btw. you can also pass the data as second parameter:

$('<div />', {'class': 'error', text: 'Error-Homie!'})

这篇关于jQuery的:当创建一个新的元素,我是否需要结束标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆