Javascript javascript更改按钮的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10215792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:21:04  来源:igfitidea点击:

javascript change value of button

javascripthtmlforms

提问by droidus

How do I change the value of this button? I am looking at a tutorial, but only the url seems to change, and not the button.

如何更改此按钮的值?我正在查看教程,但似乎只有 url 发生了变化,而按钮没有发生变化。

<form name="form" id="form">
<button name="button" id="button">Click Me!</button>
</form>

<script type="text/javascript">
document.form.button.value=new Date();
</script>

回答by Jonathan Payne

I added an onclick to your button to change the value with the function.

我在您的按钮上添加了一个 onclick 以使用该函数更改值。

If you add onsubmit="return false"to the form tag, it won't refresh the page.

如果您添加onsubmit="return false"到表单标签,它不会刷新页面。

<form name="form" id="form" onsubmit="return false">
    <button name="button" id="button" onclick="changeValue();" value="before" >Click Me!</button>
</form>

<script type="text/javascript">
    function changeValue()
    {
        // Changes the value of the button
        document.form.button.value = new Date();

        // Changes the text on the button
        document.form.button.innerHTML = new Date();
    }
</script>

回答by Travesty3

document.form.button.innerHTML = new Date();



EDIT:编辑:

If what you're trying to is to make the text on the button change to the current date when you click it, this is what you want to do:

如果您想要的是在单击按钮时将按钮上的文本更改为当前日期,那么这就是您想要执行的操作:

<script type="text/Javascript">
    function changeLabel()
    {
        document.getElementById('button').innerHTML = new Date();
    }
</script>

<button id="button" onclick="changeLabel()">Click Me!</button>

回答by Travesty3

This works for sure...

这肯定有效...

onclick="changeValue(this);"

function changeValue(button)
{
    // Changes the value of the button
    button.value = new Date();
}

回答by Engineer

Use innerHTML:

使用innerHTML

document.form1.button1.innerHTML=new Date();

UPDATE:Alternative you could define your button like:

更新:或者,您可以定义您的按钮,如:

<input name="button" id="button" type="button" value="Click Me!" />

In that case

在这种情况下

document.form.button.value=new Date();

should work as you had expected .

应该像你预期的那样工作。