2014-11-04 61 views
4

我試圖在不刷新頁面的情況下動態使用Javascript將元素放入其他元素中,它的AJAX部分起作用並且功能正常。但是由於某些未知的原因,我的代碼會自動關閉。Javascript - .innerHTML更改自動關閉標記

下面是代碼片段,你可以看到它沒有真正關閉。但是,在瀏覽器中運行的代碼後,關閉

HTML

<div id="Events"> 

的Javascript

Get = document.getElementById("Events"); 
Get.innerHTML = "<div class='large-6 columns Pages' id='Page" + PN + "' style='background-color: #" + i + i + i + ";'>"; 
Get.innerHTML = Get.innerHTML + "<div class='large-6 columns Pages' id='Page" + PN + "' style='display: none; background-color: #" + i + i + i + ";'>"; 

頁面源的結果是:

<div id="Page1" class="large-6 columns Pages" style="background-color: #000;"></div> 
<div class="EventsClass"></div> 

正如你所看到的,這是一個問題,因爲我試圖將元素放入元素中。但我不能因結束標籤。

我搜索了幾個小時,找不到解決方案,甚至是導致此問題的原因。 沒有結束標籤,但它自動關閉。有沒有辦法來覆蓋這個?還是繞過它?

+0

你可以發佈你的代碼在jsfiddle。爲什麼你的變量名爲get? Get和Post通常用於表示Http方法 – 2014-11-04 06:03:16

回答

9

documentation

innerHTML屬性設置或返回一個元素的HTML內容(內HTML)。

顯然,此屬性返回的內容必須是結構良好的HTML肯定會通過瀏覽器關閉標籤來呈現。

如果要使用元素內的元素並更新所需GET對象的HTML。只要創建一個普通的字符串變量的是,你要添加的內容,然後消毒它以後,當你有你想要的全部內容,然後用類似更新.innerHTML

//content is a variable that just holds the string representing the HTML Content 

    var content = "<div class='large-6 columns Pages' id='Page" + PN + "' style='background-color: #" + i + i + i + ";'>"; 
    content += "<div class='large-6 columns Pages' id='Page" + PN + "' style='display: none; background-color: #" + i + i + i + ";'>"; 

    //close the divs or add more elements to the variable content 

    Get.innerHTML = content; //At the end. 

希望這讓你開始朝正確的方向發展。

+0

像魅力一樣工作。沒有意識到你不能插入破碎的HTML。將來會記住它。感謝Vivek! – Hamedar 2014-11-04 06:18:49