Javascript 在 jQuery 中创建 DOM 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6902778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:41:19  来源:igfitidea点击:

Creating DOM elements in jQuery

javascriptjquery

提问by Jay Sun

Let's say we have the following JavaScript/jQuery code below

假设我们有以下 JavaScript/jQuery 代码

function createElement(i, value) {
    return $('<div>', { id: "field" + i, text: value});
}

I have a div with an id of "container" and then I do:

我有一个 ID 为“容器”的 div,然后我执行以下操作:

var c=$("container");
c.append(createElement(1, "hello, world!");

Now I've got 2 questions

现在我有2个问题

  1. Does the createElement function use jQuery to return an HTML string that gets appended to container or does it dynamically create a DOM element that gets appended to the container?

  2. I'm unfamiliar with this kind of jQuery where you actually create the HTML string (or DOM element) via the $() selector. I tried looking for the documentation on this subject in jQuery's website but I couldn't find it. Can somebody point me in the right direction?

  1. createElement 函数是使用 jQuery 返回附加到容器的 HTML 字符串还是动态创建附加到容器的 DOM 元素?

  2. 我不熟悉这种通过 $() 选择器实际创建 HTML 字符串(或 DOM 元素)的 jQuery。我尝试在 jQuery 的网站上查找有关此主题的文档,但找不到。有人可以指出我正确的方向吗?

采纳答案by Dogbert

  1. It creates the DOM element on the fly, and appends that.

  2. http://api.jquery.com/jQuery/#jQuery2

  1. 它动态创建 DOM 元素,并附加它。

  2. http://api.jquery.com/jQuery/#jQuery2

回答by MaxiWheat

  1. In fact it creates the DOM element + it returns a jQuery object which contains your DOM element you just created.
  2. Dogbert was right about this, the doc is here
  1. 事实上,它创建了 DOM 元素 + 它返回一个 jQuery 对象,其中包含您刚刚创建的 DOM 元素。
  2. Dogbert 是对的,医生在这里