javascript - 如何正确命名以编程方式创建的标签

标签 javascript jquery

众所周知,我们可以通过以下代码创建新元素:

$('<div/>', {
  style: 'display: inline-block;'
})

但我想知道,是否有关于如何创建它们的规则?

我应该像这样作为第一个参数(标签名称)字符串传递 -- <div/> ?或者也许像这样 - <div> ?或者甚至像这样-div

从文档中我不清楚。

最佳答案

documentation对此其实是很清楚的。它期望 htmlString :

A string is designated htmlString in jQuery documentation when it is used to represent one or more DOM elements, typically to be created and inserted in the document. When passed as an argument of the jQuery() function, the string is identified as HTML if it starts with ) and is parsed as such until the final > character.

所以你不能使用div因为这实际上会搜索所有现有的 <div>在你的 DOM 中。

it also says :

When the parameter has a single tag (with optional closing tag or quick-closing) — $( "<img />" ) or $( "<img>" ), $( "<a></a>" ) or $( "<a>" ) — jQuery creates the element using the native JavaScript .createElement() function.

那里清楚地表明关闭标签是可选的。所以 <div> 之一或<div />很好。

关于javascript - 如何正确命名以编程方式创建的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38997409/

相关文章:

php - jQuery 和 ajax 在 jQuery UI 对话框小部件中更新 MySQL 中的行

javascript - HTML Select 中的排序选项

javascript - 平移至 Google map 的 "usable part"

javascript - 根据纬度和经度确定哪个是多边形

javascript - 使用ajax发送多个变量的最佳实践

javascript - 使用 FancyBox 出现 jQuery 未定义错误

jquery - 不引人注目的验证不适用于 MVC 4 中的 Textarea

javascript - 开发webusb api时未能声明接口(interface)

javascript - 在 Meteor 1.3 中导入通过 npm 安装的外部 Javascript 库

javascript - 在 TypeScript 中扩展 Error 类时,接口(interface)不被应用