[英]What is the easiest way to add an element to html through javascript
似乎有很多方法可以做到這一點,但是,它們都沒有對我有意義。 如果有人能給我一個例子來說明如何添加一個標簽並編輯它的屬性(沒有document.write亂七八糟),它適用於所有常見的瀏覽器但 IE瀏覽器,這將是很棒的。
編輯
我根本不在乎它是否適用於IE。 如果確實如此,那很好,但我不喜歡IE,無論如何我只會要求人們更改瀏覽器,因為我正在創建的頁面上的其他內容在IE中不起作用。
這是如何創建<div>
元素並將其添加到布局的最簡單示例。
var el = document.createElement("div"); // creating element
el.setAttribute("class", "myClass"); // setting attribute "class"
el.innerHTML = "Text"; // adding text inside the element
document.body.appendChild(el); // appending new element to page body
演示: http : //jsfiddle.net/XVaqY/
要使它在IE中不起作用,請添加任何瀏覽器檢查。 像這樣的東西:
function isIE() {
return (navigator.appName == "Microsoft Internet Explorer");
}
這是一個使用javascript添加DIV的工作示例
<html>
<head>
<title>Javascript Create Div Element Dynamically</title>
<style type="text/css">
.dynamicDiv {
width: 200px;
height: 100px;
border: solid 1px #c0c0c0;
background-color: #e1e1e1;
font-size: 11px;
font-family: verdana;
color: #000;
padding: 5px;
}
</style>
<script type="text/javascript" language="javascript">
function createDiv() {
var divTag = document.createElement("div");
divTag.id = "div1";
divTag.setAttribute("align", "center");
divTag.style.margin = "0px auto";
divTag.className = "dynamicDiv";
divTag.innerHTML = "This HTML Div tag created "
+ "using Javascript DOM dynamically.";
document.body.appendChild(divTag);
}
</script>
</head>
<body>
<p align="center">
<b>Click this button to create div element dynamically:</b>
<input id="btn1"
type="button"
value="create div"
onclick="createDiv();" />
</p>
</body>
</html>
首先,使用document.createElement()
創建元素並將其保存到變量中。 此時它尚未在DOM中。 然后,根據需要更改其屬性,然后在您喜歡的任何位置將其插入DOM。 在我的示例中,它將在body
標記的末尾插入id
為elementid
的DIV
元素。
var newDiv = document.createElement("div");
newDiv.id = "elementid";
document.body.appendChild(newDiv);
以下是一些向DOM添加內容的方法:
使用W3C推薦的方法:
var heading = document.createElement("h1");
heading.createTextNode("Foobar");
heading.className = "semantic-class-name-goes-here";
heading.setAttribute("aria-something-here", "bar");
使用innerHTML:
document
.innerHTML("<h1 class='semantic-class-name-goes-here' aria-something-here='bar'>Foobar</h1>");
使用jQuery:
var heading = $("h1")
.addClass("semantic-class-name-goes-here")
.attr("aria-something-here", "bar");
$(document).append(heading);
假設您要排除所有IE版本,可以使用webreflection博客中的這個技巧
if (!(!+"\v1")) {
var el = document.createElement("div");
...
document.body.appendChild(el);
}
或者,檢測IE的另一個條件也可以是
if (!top.execScript) { ... }
甚至
var isIE = /*@cc_on!@*/!1;
if (isIE) { ... }
但說實話,他們對我來說太苛刻了。
無論如何,如果你指定排除IE的技術原因,並告訴我們你想要完成什么樣的功能,可能有可能根據特定的IE限制為你提供更安全的方法來完成這項任務(功能優於瀏覽器嗅探)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.