我有一个简单的textarea:
<textarea rows="10%" cols="100%" id="myTextArea">
每当我点击一个按钮时,我都有一个改变textarea值的函数。问题是我失去了旧值的旧价值。有办法保留所有这些吗?
function changeTextAreaValue1(){
document.getElementById("myTextArea").value = "value1";
}
function changeTextAreaValue2(){
document.getElementById("myTextArea").value = "value2";
}
changeTextAreaValue1();
changeTextAreaValue2();
我用这个简单的jsfiddle来说明:https://jsfiddle.net/syLuLob0/201/
提前谢谢
答案 0 :(得分:2)
function changeTextAreaValue1(){
document.getElementById("myTextArea").value = "value1";
}
function changeTextAreaValue2(){
var oldVal = document.getElementById("myTextArea").value;
document.getElementById("myTextArea").value = oldVal +"value2";
}
changeTextAreaValue1();
changeTextAreaValue2();
<textarea rows="10%" cols="100%" id="myTextArea"></textarea>
答案 1 :(得分:0)
因为您要替换文本,所以需要连接到现有文本。
var ele = document.getElementById("myTextArea");
function changeTextAreaValue1(){
ele.value += "value1"; // See the +
}
function changeTextAreaValue2(){
ele.value += "value2";
}
changeTextAreaValue1();
changeTextAreaValue2();
答案 2 :(得分:0)
var el = document.getElementById("myTextArea"),
previousValue;
function changeTextAreaValue (val) {
previousValue = el.value;
el.value = val;
}
changeTextAreaValue("hello");
changeTextAreaValue("world");
// previousVar is now "hello"