通过这个简单的例子,我希望p元素获得文本输入的当前值,但无法弄清楚。价值不会改变。
function myFunction() {
document.getElementById("myText").value = "Johnny Bravo";
}
document.getElementById("p1").innerHTML = document.getElementById("myText").value;

Name: <input type="text" id="myText" value="Mickey">
<p id="p1">Click the button to change the value of the text field.</p>
<button onclick="myFunction()">Try it</button>
&#13;
答案 0 :(得分:3)
将部分代码移到函数内部。目前,它只运行一次,而不是在单击按钮后再次运行。
function myFunction() {
document.getElementById("myText").value = "Johnny Bravo";
document.getElementById("p1").innerHTML = document.getElementById("myText").value;
}
&#13;
Name: <input type="text" id="myText" value="Mickey">
<p id="p1">Click the button to change the value of the text field.</p>
<button onclick="myFunction()">Try it</button>
&#13;
答案 1 :(得分:3)
function myFunction() {
document.getElementById("p1").innerHTML = document.getElementById("myText").value;
}
Name: <input type="text" id="myText" value="Mickey">
<p id="p1">Click the button to change the value of the text field.</p>
<button onclick="myFunction()">Try it</button>
答案 2 :(得分:2)
切换JS中的两行代码的位置......
function myFunction() {
document.getElementById("p1").innerHTML = document.getElementById("myText").value;
}
document.getElementById("myText").value = "Johnny Bravo";
我猜你想以Johnny Bravo的身份开始贬值,然后点击按钮,然后设置innerHTML?