Javascript 在 Jquery 中创建元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12143106/
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
Create Element in Jquery
提问by Matt
I would like to create element in Jquery/Javascript by using "div.someelement" like this
我想通过像这样使用“div.someelement”在 Jquery/Javascript 中创建元素
var SomeElement = $("div.someelement");
$( "#container" ).append( SomeElement );
But I don't want to copy element with the same class, I would like to create new one.
但我不想复制具有相同类的元素,我想创建一个新元素。
document.createElement
is creating "<div.somelement>"
instead of <div class="someelement">
document.createElement
正在创造"<div.somelement>"
而不是<div class="someelement">
回答by Jishnu A P
I would use the following method to create elements on the fly
我将使用以下方法动态创建元素
$("<div/>",{
"class" : "someelement",
// .. you can go on and add properties
"css" : {
"color" : "red"
},
"click" : function(){
alert("you just clicked me!!");
},
"data" : {
"foo" : "bar"
}
}).appendTo("#container");
回答by iambriansreed
Try this:
尝试这个:
var $someelement = $('<div class="someelement"/>').appendTo('#container');
This will create a brand new element inside of #container
and save it as $someelement
for easy reference later.
这将在其中创建一个全新的元素#container
并将其保存以$someelement
供日后参考。
http://api.jquery.com/jQuery/#jQuery2
http://api.jquery.com/jQuery/#jQuery2
UPDATE
更新
You could clone the original then empty it out. This doesn't affect the original element at all.
您可以克隆原件然后将其清空。这根本不会影响原始元素。
var $someelement = $('div.someelement').clone().empty().appendTo('#container');
回答by Fidi
You can do this by the following:
您可以通过以下方式执行此操作:
var newElement = $('<div class="someelement"></div>');
$('#container').append(newElement);
or if you don't need the element you can directly append it:
或者如果您不需要该元素,您可以直接附加它:
$('#container').append('<div class="someelement"></div>');
回答by Waleed Khan
Use this:
用这个:
var someElement = $("<div></div>");
someElement.addClass("someelement");
$("#container").append(someElement);
Or you can chain together the calls:
或者您可以将调用链接在一起:
$("#container").append(
$("<div></div>")
.addClass("someelement")
);
EDIT:
编辑:
Perhaps I misunderstood the question, maybe this will help. To create a new set of elements, use jQuery's clone
method:
也许我误解了这个问题,也许这会有所帮助。要创建一组新元素,请使用 jQuery 的clone
方法:
$("div.someelement").clone().appendTo("#container");
回答by gray state is coming
According to the question you want to use a syntax like "div.someelement"
to create an element.
根据您要使用的语法"div.someelement"
来创建元素的问题。
In order to do that, you need to make your own parser.
为此,您需要制作自己的解析器。
It is very simple if that will be the exact syntax.
如果这将是确切的语法,那就非常简单了。
var str = "div.someelement",
parts = str.split("."),
elem = $("<" + parts.shift() + ">"),
cls;
while (cls = parts.shift())
elem.addClass(cls);
But if you're going to do this, you might as well use native methods.
但是,如果您打算这样做,您不妨使用本机方法。
var str = "div.someelement",
parts = str.split("."),
elem = document.createElement(parts.shift());
elem.className = parts.join(" ");
If you want to allow for full CSS syntax for creating an element, then you may want to look at the regex parser that Sizzle uses, and use it for your needs.
如果您想允许使用完整的 CSS 语法来创建元素,那么您可能需要查看 Sizzle 使用的正则表达式解析器,并根据您的需要使用它。
回答by J. Holmes
I would use zen coding for textareaas a starting point. Its syntax is close enough for what you are trying to do, its a well understood implementation. You should be able to invoke the transformation from a raw string rather than from a textarea with a little tweaking.
我将使用禅宗编码作为起点。它的语法对于您要执行的操作来说足够接近,它是一个很好理解的实现。您应该能够通过稍加调整从原始字符串而不是从文本区域调用转换。
回答by gray state is coming
Since you are asking about creating an element from css syntax, you need to use a parser to interpret the syntax.
由于您问的是从 css 语法创建元素,因此您需要使用解析器来解释语法。
Here is an example you can build from. This will match an element name followed by id, class or other attributes. It won't cover some edge cases, but will work in most cases.
这是您可以从中构建的示例。这将匹配元素名称后跟 id、class 或其他属性。它不会涵盖某些边缘情况,但会在大多数情况下工作。
var elem_regex = /^(\w+)?|(#|\.)([^.#\[]+)|(\[[^\]]+?\])/g
Then make a function to get the parts and create an element.
然后创建一个函数来获取零件并创建一个元素。
function elementFromSelector(str) {
var match, parts = {}, quote_re = /^("|').+()$/;
while (match = elem_regex.exec(str)) {
if (match[1])
parts.name = match[1];
else if (match[2] === ".") {
if (!parts.clss)
parts.clss = [];
parts.clss.push(match[3]);
} else if (match[2] === "#")
parts.id = match[3];
else if (match[4]) {
var attr_parts = match[4].slice(1,-1).split("="),
val = attr_parts.slice(1).join("");
parts[attr_parts[0]] = quote_re.test(val) ? val.slice(1,-1) : val;
}
else throw "Unknown match";
}
if (parts.name) {
var elem = document.createElement(parts.name);
delete parts.name;
for (var p in parts)
if (p === "clss")
elem.className = parts[p].join(" ");
else
elem[p] = parts[p];
return elem;
} else throw "No element name at beginning of string";
}
Then pass a proper string to the function, and it will return the element.
然后将适当的字符串传递给函数,它将返回元素。
var str = 'input#the_id.firstClass.secondClass[type="text"][value="aValue"]';
var element = elementFromSelector(str);
Before creating the element, the parts look like this.
在创建元素之前,部件看起来像这样。
{
"name": "input",
"id": "the_id",
"clss": [
"firstClass",
"secondClass"
],
"type": "text",
"value": "aValue"
}
Then it uses that info to create the element that gets returned.
然后它使用该信息来创建返回的元素。
回答by Patrick Bentveld
Simply create a new Element for jQuery:
只需为 jQuery 创建一个新元素:
var $newElement = $(document.createElement("div"));
$newElement.appendTo($("body"));
if you want to at attributes to de element simplie use:
如果你想在属性上简单地使用 de 元素:
$newElement.attr({
id : "someId",
"class" : "someClass"
});
Rember by class always use like this "class", because class is a reserved name
Rember by class 总是像这样使用“class”,因为 class 是一个保留名称