简体   繁体   English

如何安全地使用innerHTML?

[英]How to use innerHTML safely?

Instead of retyping repeated codes for a side bar in Javascript, I made a sidebar function which is used to populate similar codes for every pages.我没有为 Javascript 中的侧边栏重新输入重复代码,而是制作了一个侧边栏 function 用于为每个页面填充类似的代码。 it looks like this:它看起来像这样:

function addSidebarTemplate(){
      const template = document.createElement('template');
      template.innerHTML = `<aside class="aside-container">
                            <header>
                <a href="."> link here</a>
                <a class="mr-1" href="#">
                    <i class="fab fa-linkedin"></i>
                </a>
                <a class="mr-1" href="#">
                    <i class="fab fa-facebook"></i>
                </a>
                <a class="mr-1" href="#">
                    <i class="fab fa-github"></i>
                </a>
                 </header>`
       document.querySelector('#sidebar').appendChild(sidebar.content);

There are other elements below this code.此代码下方还有其他元素。 But none of them requires user's input.但它们都不需要用户输入。 I just wonder is this safe to use innerHTML in this case?我只是想知道在这种情况下使用 innerHTML 是否安全? If not, is there better way to insert the side bar like this?如果没有,有没有更好的方法来插入这样的侧栏?

Thanks谢谢

If no user input is used, then innerHTML is fine to use.如果不使用用户输入,则可以使用innerHTML That being said, if you're doing a lot of this you may want to look into using a UI library like React to help you out.话虽如此,如果你做了很多这样的事情,你可能想考虑使用像 React 这样的 UI 库来帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM