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
Creating DOM elements in jQuery
提问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个问题
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?
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?
createElement 函数是使用 jQuery 返回附加到容器的 HTML 字符串还是动态创建附加到容器的 DOM 元素?
我不熟悉这种通过 $() 选择器实际创建 HTML 字符串(或 DOM 元素)的 jQuery。我尝试在 jQuery 的网站上查找有关此主题的文档,但找不到。有人可以指出我正确的方向吗?
采纳答案by Dogbert
It creates the DOM element on the fly, and appends that.
它动态创建 DOM 元素,并附加它。
回答by MaxiWheat
- In fact it creates the DOM element + it returns a jQuery object which contains your DOM element you just created.
- Dogbert was right about this, the doc is here
- 事实上,它创建了 DOM 元素 + 它返回一个 jQuery 对象,其中包含您刚刚创建的 DOM 元素。
- Dogbert 是对的,医生在这里