为什么将动态textarea附加到div会产生空文本区域?

时间:2015-09-19 06:01:11

标签: javascript jquery

我只是试图在一个名为post的div中编辑一个名为元描述的div,通过获取html并用它创建一个textarea然后将其重新插入。我让它为Title,content甚至meta工作关键字,但由于某种原因,描述的textarea最终会变得空洞。

    //---------------edit meta Description------------
var Description = metaDescription;
Description.show();
//save the html within the div
var ogDescription = "None"; 
if (metaDescription.html()) {
    ogDescription = $(Description).html().trim();
}
console.log('ogDescription = ' + ogDescription); 
// create a dynamic textarea
var editDescription = $("<textarea />"); 
editDescription.val(ogDescription);
console.log('editDescript val after adding === ' + editDescription.val());
console.log('editDescript html after adding === ' + editDescription.html());
editDescription.attr('class', 'editDescription')
            .css('height', metaHeight)
            .css('width', post.css('width')); 
// add the textarea 
Description.html("<p>meta Description:</p>"); 
$(Description).append(editDescription); 
//--end edit meta Description

输出

Title = Newly Added Post
Posts.js:79 Content = Testing 1, 2, 3
Posts.js:105 ogDescription = Testing 1,2 and u know 3
Posts.js:110 editDescript val after adding === Testing 1,2 and u know 3
Posts.js:111 editDescript html after adding === 
Posts.js:129 Keywords = none, for, now
Description html after === <p>meta Description:</p><textarea class="editDescription" style="height: 80px; width: 262px;"></textarea>

2 个答案:

答案 0 :(得分:0)

Textarea没有值属性。与输入不同,textarea的“值”是开始和结束标记之间的内容。你需要使用.html(“blah”)或.text(“blah”)来设置innerHtml

请参阅Set value of textarea in jQuery

答案 1 :(得分:0)

尝试按如下方式创建textarea

var editDescription = $("<textarea>" + ogDescription + "</textarea>");