代码之家  ›  专栏  ›  技术社区  ›  iLearn2016

使用javascript innerHTML清理注射用html?

  •  1
  • iLearn2016  · 技术社区  · 7 年前

    需要修复下面的函数以在内部清理html listStr ,尝试了各种HTML转义函数( listDom.innerHTML = escapeHTML(listStr);

        function createList(list) {
            let listStr = "";
    
            list.forEach(function (item) {
    
                if (item.click) {
                    var clean_url = encodeURIComponent(item.href);
                    clean_url = "";
                    //console.log(clean_url);
                    listStr += `<div class='list_item' id="${item.uid}"><a href="javascript:void(0);">${item.label}</a></div>`;
    
                } else {
                    //'loop', i + ''
                    listStr += `<div class='list_item' id="${item.uid}" loop="${item.loop}"><a href="${item.href}">${item.label}</a></div>`;
                }
            });
    
            listStr += '';
    
            let listDom = document.createElement("div");
            listDom.setAttribute("id", "list");
            listDom.setAttribute("style", "display: none;");
            listDom.innerHTML = listStr;
    
            return listDom;
        }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   iLearn2016    7 年前

    我最后是这样做的:

                    let listItem = document.createElement('div');
                    listItem.setAttribute('class', 'list_item');
                    listItem.setAttribute('id', item.uid);
    
                    let linkItem  = document.createElement('a');
                    linkItem.setAttribute('href', 'javascript:void(0);');
                    linkItem.innerText = item.label;
    
                    listItem.appendChild(linkItem);
                    listStr.appendChild(listItem);