Javascript - .innerHTML更改自动关闭标签 [英] Javascript - .innerHTML changes auto close tags

查看:96
本文介绍了Javascript - .innerHTML更改自动关闭标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在不刷新页面的情况下使用Javascript动态地将元素放入其他元素中,它的AJAX部分起作用并且功能正常。然而,由于某些未知的原因,我的代码会自动关闭。

I'm trying to put elements inside other elements dynamically using Javascript without refreshing the page, the AJAX part of it works and is functional. However for some unknown reason my code closes automatically.

以下是代码片段,您可以看到它没有真正关闭。但在浏览器中运行代码后,它已关闭

Here is a snippet of the code, and you can see that it's no actually closed. But after running the code in a browser it is closed

HTML

<div id="Events">

Javascript

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>

正如您所看到的,这是一个问题,因为我试图将元素放入元素中。然而,我不能因结束标签。

As you can see, this is a problem as I am trying to put elements inside elements. However I can't due to the closing tags.

我搜索了几个小时,找不到解决方案,甚至是导致此问题的原因。
没有结束标记,但它会自动关闭。有没有办法来覆盖这个?或绕过它?

I've search for a few hours and can't find a solution or even a cause to this. There is NO closing tags, yet it is closed automatically. Is there a way to override this? Or bypass it?

推荐答案

来自文档


innerHTML 属性设置或返回一个元素的HTML内容(内部HTML)。

The innerHTML property sets or returns the HTML content (inner HTML) of an element.

显然,这个属性返回的内容必须是

Clearly, the content returned by this property has to be well-formed HTML and will definitely be rendered by browser with closing tags.

如果您想使用元素内的元素并更新 HTML 您想要的 GET 对象。只需从要添加的内容中创建一个普通的字符串变量,然后再进行清理,当您拥有完整的内容时,请更新 .innerHTML 类似的东西:

If you want to use elements inside elements and update the HTML of your desired GET object. Just create a normal string variable out of the content that you want to add and then sanitize it later on, and when you have the complete content that you desire, then update the .innerHTML with something like:

    //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.

我希望这能让您开始朝正确的方向前进。

I hope this gets you started in the right direction.

这篇关于Javascript - .innerHTML更改自动关闭标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆