使用getElementById时document.open的替代方法?

时间:2014-01-07 16:39:18

标签: javascript elements

我过去常常使用document.write()而不是document.getElementById(),当我使用document.write()时,我可以公开使用document.open(),这意味着我可以拥有不同的页面,但仍然保留同一页面(.html)。我已经尝试了很多东西,比如隐藏元素,但这使得它们上的链接仍然可以点击。

我希望实现相同的目标,但仍然使用良好的做法。

这是我以前做的事情;

document.write("Hey!");
document.write('<button onclick="bye()">');

function bye() {
    document.open()
    // Clears page
    document.write("Bye");
}

2 个答案:

答案 0 :(得分:0)

请勿使用document.write()。相反,我只是使用document.body.innerHTML"",并将内容附加到innerHTML,就像这样

function bye(){
     document.body.innerHTML=""; //clears page
     document.body.innerHTML+="Bye";
}

或者你可以将两者结合成

document.body.innerHTML="Bye";

答案 1 :(得分:0)

如果您询问如何附加元素并将其从页面中删除而不必使用document.write,则可以使用document.createElement()

来执行此操作

考虑这个例子:

add按钮会创建div,然后将其附加到名为div的页面中的另一个targetremove将移除target div的第一个子元素。

<!DOCTYPE html>
<html>
   <head>
      <title>Div Controller</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width">
      <script>
         function main() {
            document.getElementById("add").addEventListener("click", function() {
               var newDiv = document.createElement("div");
               newDiv.innerHTML = "I'm a div";
               document.getElementById("target").appendChild(newDiv);
            });
            document.getElementById("remove").addEventListener("click", function() {
               var target = document.getElementById("target");
               if (target.firstChild) {
                  target.removeChild(target.firstChild);
               }
            });
         }

         window.onload = main;
      </script>
   </head>
   <body>
      <div id="target"></div>
      <button id="add">Add</button>
      <button id="remove">Remove</button>
   </body>
</html>