简体   繁体   English

在javascript中制作按钮显示文本

[英]Making a button display text in javascript

I'm trying to display a number (1, 2, or 3) in my html file when I click a button.当我单击一个按钮时,我试图在我的 html 文件中显示一个数字(1、2 或 3)。

Here is what I have so far:这是我到目前为止所拥有的:

<tr>
    <td><button onclick="setDay(1)">1</button></td>
    <td><button onclick="setDay(2)">2</button></td>
    <td><button onclick="setDay(3)">3</button></td>
</tr>

<script type="text/javascript">
    function setDay(a) {
        var day = a
    }
    document.write(day)
</script>

I want to have it so when I click "button '1' ", for example, the function setDay() runs, with my argument set to 1. This way, the variable "day" is set to 1, and then when the variable 'day' is printed the number 1 is displayed.我想要它,所以当我点击“button '1'”时,例如,函数 setDay() 运行,我的参数设置为 1。这样,变量“day”设置为 1,然后当变量 'day' 被打印,数字 1 被显示。 Any help would be greatly appreciated.任何帮助将不胜感激。

There are multiple things wrong with your code:您的代码有很多问题:

  1. You are declaring the day variable inside your function, so whenever the function completes, the variable will be destroyed.你在你的函数中声明了 day 变量,所以只要函数完成,变量就会被销毁。 So to persist it, move it outside the function and set it from inside.所以要坚持它,把它移到函数外面并从里面设置它。

  2. document.write will clear your document and replace it with whatever you specify. document.write将清除您的文档并将其替换为您指定的任何内容。 Hence you need to have another element on which you can display the day.因此,您需要有另一个可以显示日期的元素。

The code should be:代码应该是:

 var day; function setDay(a) { day = a; document.getElementById('day').innerHTML = day; }
 <tr> <td><button onclick="setDay(1)">1</button></td> <td><button onclick="setDay(2)">2</button></td> <td><button onclick="setDay(3)">3</button></td> </tr> Day : <p id='day'></p>

The document.getElementById('day') gets the element where you want to display your day, a paragraph tag here, and sets its innerHTML or the html inside the element to be the specified day. document.getElementById('day')获取要显示日期的元素,此处为段落标记,并将其innerHTML或元素内的html 设置为指定的日期。

It's not clear whether you want the 1,2,3 to appear on the buttons when clicked or in a new spot.不清楚您是否希望 1,2,3 在单击时出现在按钮上或出现在新位置。 either way you want to pass the event and the number to your function.无论哪种方式,您都希望将事件和数字传递给您的函数。 Then set innerHTML of the element you want the number to appear in.然后设置要显示数字的元素的innerHTML。

 function setDay(event,a) { e=event.target; e.innerHTML = a; var div = document.getElementById('here'); var text = div.innerHTML; div.innerHTML = text + " " + a; }
 button{ height:36px; width:36px; vertical-align:top; }
 <tr> <td><button onclick="setDay(event,1)"></button></td> <td><button onclick="setDay(event,2)"></button></td> <td><button onclick="setDay(event,3)"></button></td> </tr> <div id="here"></div>

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

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