在 onClick 上更改 javascript 中的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5441008/
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-23 17:12:32  来源:igfitidea点击:

Making on onClick to change text in javascript

javascript

提问by Jono

I want to make a format like the following:

我想制作如下格式:

Phrase
[Button]

短语
[按钮]

When the button is clicked, the 'phrase' changes and the button remains. I am able to make it so text appears, however I can not make it so the button stays. Does anyone have an idea of how this may be done? Thanks.

单击按钮时,“短语”会发生变化,而按钮会保留。我可以让它显示文本,但是我不能让它保留按钮。有没有人知道如何做到这一点?谢谢。

采纳答案by Can't Tell

Take a look at this.

看看这个

回答by Jono

Final script

最终剧本

Javascript (replacement)

Javascript(替换)

function displayPhrase()
{
    document.getElementById("demo").innerHTML = 'New Phrase';
}

HTML (Old phrase)

HTML(旧词组)

<span id="demo">Old Phrase</span>

HTML (The button)

HTML(按钮)

<button type="button" onclick="displayPhrase()"></button>

Credit to above answers ^_^

归功于以上答案^_^

回答by alex

I am able to make it so text appears, however I can not make it so the button stays.

我可以让它显示文本,但是我不能让它保留按钮。

My guess is you are updating the element that also contained the buttonelement, and this update is clearing the button.

我的猜测是您正在更新也包含该button元素的元素,并且此更新正在清除button.

HTML

HTML

<span id="phrase"></span>
<button id="change-phrase" type="button">Change Phrase</button>

JavaScript

JavaScript

var button = document.getElementById('change-phrase'),
    content = document.getElementById('phrase');

button.onclick = function() {
    content.innerHTML = 'Your new phrase';
};

jsFiddle.

js小提琴

回答by Bal mukund kumar

Use this code:

使用此代码:

HTML:

HTML:

<h1> Welcome to the </h2><span id="future-clicked"></span>

<button onclick="clicked_on()">Click for future</button>

JS:

JS:

<script>
    function clicked_on(){
        document.getElementById('future-clicked').innerHTML = 'Future World';
    }
</script>