首页 > 解决方案 > 单击按钮以更新 JavaScript 中的文本

问题描述

<div id="div1"></div>
<button id="addText" onclick="addText()">Add Text</button><br>

我试图让这个按钮调用这个函数来更新一个文本字段。我不希望它进入操作页面或任何东西。显示方面甚至都不重要。我只是想找出如何通过单击按钮在后台更新变量。

function addText(){
    // create a new div element 
    var newDiv = document.createElement("div"); 
    // and give it some content 
    var newContent = document.createTextNode("Hi there and greetings!"); 
    // add the text node to the newly created div
    newDiv.appendChild(newContent);  
    // add the newly created element and its content into the DOM 
    var currentDiv = document.getElementById("div1"); 
    document.body.insertBefore(newDiv, currentDiv); 
}

标签: javascript

解决方案


尝试这个

function addText(){
    document.getElementById("div1").innerHTML = "your change text";
}

推荐阅读