使用document.write会删除所有其他文本并仅显示该消息

时间:2017-08-22 18:33:57

标签: javascript html css

我刚才有一个关于如何制作它的问题,以便在一列中有一个按钮,当您单击该按钮时,文本会出现在另一列中。我的总体目标是制作一个简单的点击器。

这是我的代码:

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Clicker</title>
        <meta name="generator" content="BBEdit 11.6" />
    </head>
    <body>
        <table width=600>
            <tr>
                <td width=300><span><font size=24px><button onclick='onClick()'>
                    click me
                    </button></span></td>
                <td sidth=300><span><font size=24px>So does this</span></td>
            </tr>
        </table>
    <script>
        clicks = 0;

            function onClick () {
                clicks = (clicks + 1);
                document.write ("you have clicked the button ")
                document.write (clicks)
                document.write (" times")
            };

        </script>
    </body>
</html> 

我有我需要的东西,以便您在单击按钮时收到消息,但是当我这样做时,所有其他文本消息,我得到的消息。告诉我,如果这是一个非常愚蠢的错误,请不要。我需要知道。

3 个答案:

答案 0 :(得分:0)

和平,热爱一个令人困惑的问题。

&#13;
&#13;
<button onclick="a='textContent';t[a]=t[a].replace(/\d+/,++this[a])">0</button><p id=t>Total:0
&#13;
&#13;
&#13;

答案 1 :(得分:0)

单击按钮并调用counting()函数时创建一个匿名函数。这将增加变量countingClicks的值,然后将另一列中元素的innerText设置为该变量。

&#13;
&#13;
var x = document.getElementById("counter");
var y = document.getElementById("display");
var countingClicks = 0;

function counting() { 
  countingClicks++;
  y.innerText ="Number of times clicked: " + countingClicks;
}

//When the counter button is clicked call counting
x.onclick = function(){
	counting()
}
&#13;
.container{
  width: 600px;
  box-sizing: border-box;
}

.row{
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}

.six{
  width: 48.33%;
  text-align: center;
  border: 1px solid black;
}
&#13;
<div class="container">
  <div class="row">
    <div class="six">
      <button id="counter">Counter</button>
    </div>
    <div class="six">
      <span id="display"></span>
    </div>
  </div>
</div>
      
&#13;
&#13;
&#13;

答案 2 :(得分:0)

要显示页面中的点击次数,并保留html,一种简单的方法就是添加div并仅使用getElementById操纵其内容(以获取元素)和然后调用innerHTML(以更改HTML元素的内容)。

在你的html表中添加以下内容:

<div>
  <h1 id=click-event> </h1>   
</div>

然后更改onClick()

function onClick () {
  clicks = (clicks + 1);
  document.getElementById("click-event").innerHTML = "you have clicked the button " + clicks + " times";
};