簡體   English   中英

將HTML代碼轉換為javascript以進行動態輸入

[英]Convert html code to javascript for dynamic entry

我正在嘗試將這段html代碼轉換為javascript,以便可以將其動態添加到html代碼中的<div>

The html code is
<img src="images/bg_fav.png" alt="" width="199" height="199" class="circle"/>
<a href="#" class="icon"></a>
<h2>Filename</h2>
<ul>
<li><a href="#">Add</a></li>
</ul>

我需要將此代碼轉換為javascript。 我試圖這樣做,但似乎不起作用:

div1 = document.getElementById('div1');
a = document.createElement('img');
a.setAttribute('src','images/bg_shop.png');
a.setAttribute('alt','');
a.setAttribute('width','199');
a.setAttribute('height','199');
a.setAttribute('className','circle');

b=document.createElement('a');
b.setAttribute('className','icon');

c=document.createElement('h2');
c.value="filename";
c.name="filename";
c.id ="filename";

d=document.createElement('ul');
d.innerHTML="<li><a href='#'>add</a></li>"

div1.appendChild(a);
div1.appendChild(b);
div1.appendChild(c);
div1.appendChild(d);

您從未添加div1元素。

其他一些問題:

  • className是屬性,而不是屬性。 如果要設置屬性,請改用普通class
  • 您的h2元素正在接收nameidvalue屬性。 這些屬性沒有意義。 你的意思是:

     h2.textContent = "filename"; //innerText for IE 
  • 最后,您尚未聲明變量。 一些瀏覽器拒絕將值分配給不存在的變量。 變量由var關鍵字聲明:

     var div1 = ... 

語法為:

a.className = "circle";

要么

a.setAttribute("class","circle");

切勿混搭。

你還忽略設置href您的屬性, a標簽。

為什么要在h2上設置valuenameid 您看到<h2 value="filename" name="filename" id="filename" />嗎? 當然不是。 要么使用c.innerHTML = "Filename"; 或“適當”的方式: c.appendChild(document.createTextNode("Filename"));

聲明新變量時,請使用var :)

如果我已經有一個id為div1div ,那么對我來說可以正常工作。

看到這個小提琴

盡管也請注意Rob和Kolink關於設置屬性/類等的內容。

您只需創建所需html代碼的字符串,然后將其添加為父div的html屬性即可。 這是簡單的模板,在大多數情況下可以很好地工作。

僅當需要在運行時編輯某些屬性時,才應采用所采用的方法。 對於靜態代碼,無需采取這種復雜的方法。

function htmlToBeRendered() {
    var html =
         "<img src=\"images\\bg_fav.png\\" alt=\"\" width=\"199\" height=\"199\" class=\"circle\"/>" +
         "<a href=\"#\" class=\"icon\"></a>" +
         "<h2>Filename</h2>" +
         "<ul>" +
             "<li><a href=\"#\">Add</a></li>" +
         "</ul>";
    return html;
};

您是否嘗試過使用http://getfirebug.com/之類的開發工具進行調試? 您的頁面中是否有ID為“ div1”的元素?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM