【问题标题】:How do I change the text of a heading with a javascript button?如何使用 javascript 按钮更改标题的文本?
【发布时间】:2018-10-02 00:40:55
【问题描述】:

这里是菜鸟。 我想从一些文本中创建一个变量,这样当我点击它时,旧文本就会变成新文本。

<!DOCTYPE html>
<html>
<body>

<h1 id="id01">THis is the old text</h1>

<p>Click on "My Button" to display its value attribute.</p>

<button id="myBtn" name="myname" value="myvalue" 
onclick="alert(this.value)">My Button</button>

<p>Click on "Try it" to change the value attribute of "My Button".</p>

<button onclick="myFunction()">Try it</button>

<p><b>Tip:</b> Click on "My Button" before and after you have clicked on 
"Try it".</p>

<script>
function myFunction() {
    document.getElementById("myBtn").value = "newButtonValue";
    document.getElementById("id01").value = "this is the new text";
}
</script>

</body>
</html>

这是我使用的第一个示例,但 var = 会是更好的选择。

【问题讨论】:

    标签: javascript jquery html button text


    【解决方案1】:

    使用 innerText 而不是值。

    function myFunction() {
        document.getElementById("myBtn").value = "newButtonValue";
        document.getElementById("id01").innerText = "this is the new text";
    }
    <h1 id="id01">THis is the old text</h1>
    
    <p>Click on "My Button" to display its value attribute.</p>
    
    <button id="myBtn" name="myname" value="myvalue" 
    onclick="alert(this.value)">My Button</button>
    
    <p>Click on "Try it" to change the value attribute of "My Button".</p>
    
    <button onclick="myFunction()">Try it</button>
    
    <p><b>Tip:</b> Click on "My Button" before and after you have clicked on 
    "Try it".</p>

    【讨论】:

    • 这很完美!我希望能够有不同的文本,我如何使它使 .innertext = 一个 var 元素?
    • 只需将“this is the new text”替换为您要分配给文本的变量即可。
    猜你喜欢
    • 2011-10-25
    • 2015-11-24
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 2020-08-10
    • 2016-12-02
    相关资源
    最近更新 更多