使用javascript创建textarea [英] creating a textarea with javascript
问题描述
我正在尝试在id为body的div中创建一个文本区域。我使用onClick事件调用该函数,但是当我单击它时,创建的所有内容都是[object HTMLTextAreaElement]。我不太清楚如何让它工作。
I'm trying create a text area in a div with the id of "body". I call the function with an onClick event, but when I click it all that is created is [object HTMLTextAreaElement]. I am not quite sure how to get this to work.
function opentextarea() {
var input = document.createElement('TEXTAREA');
input.setAttribute('name', 'post');
input.setAttribute('maxlength', 5000);
input.setAttribute('cols',80);
input.setAttribute('rows', 40);
var button = document.createElement('BUTTON');
document.getElementById("body").innerHTML=input, button;
}
推荐答案
var div = document.getElementById("yourDivElement");
var input = document.createElement("textarea");
var button = document.createElement("button");
input.name = "post";
input.maxLength = "5000";
input.cols = "80";
input.rows = "40";
div.appendChild(input); //appendChild
div.appendChild(button);
如果您不需要访问特定的DOM函数,我建议使用innerHTML(因为它通常是更快,更不容易出现内存泄漏)。不要忘记妥善处理引号。为了使代码可读,您可以用加号分隔多行:
If you don't need to access specific DOM functions, I recommend to use innerHTML (because it's generally faster and less susceptible to memory leaks). Don't forget to properly deal with quotation marks. To keep the code readable, you can separate multiple lines by a plus sign:
document.getElementById("body").innerHTML =
'<textarea maxlength="5000" cols="80" rows="40"></textarea>' +
'<button></button>"':
如果要替换内容,只需使用 div.innerHTML = ;
在使用 appendChild
方法之前。
If you want to replace the contents, simply use div.innerHTML = "";
before using the appendChild
methods.
这篇关于使用javascript创建textarea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!