2014-11-04 63 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