【发布时间】:2015-03-20 03:38:09
【问题描述】:
我将 div 替换为文本输入,以便用户可以编辑文本。当用户按回车键时,我希望文本输入变回带有编辑文本的 div。
我遇到的问题是,在按 Enter 后,我无法让文本输入变回 div。我已经尝试过replaceWith() 和一些应该执行此操作的 JQuery 函数组合,但我无法弄清楚。有人可以帮忙吗?
这里是包含要编辑的评论文本的 div
<div id="comment-message-' + comment.id + '">' + comment_message + '</div>
用户点击链接编辑评论,评论变成文本输入。这很好用
<a href="javascript:editComment(' + comment.id + ');">Edit Comment</a>
这是将注释更改为文本输入的函数。这行得通
function editComment(id) {
var t = $('#comment-message-' + id).text();
$('#comment-message-' + id).replaceWith('<form id="edit-comment-form-' + id + '" name="edit-comment-form-' + id + '" action="javascript:callAPI(' + id + ')"><input id="edit-comment-' + id + '" name="edit-comment-' + id + '" type="text" value="' + t + '"/></form>');
}
我使用 Facebook API 进行调用。如果没有错误,文本输入将变为带有新注释的 div。此处的 API 调用有效,但从文本输入到 div 的更改无效
function callAPI(id) {
var e = document.getElementById('edit-comment-' + id).value,
edit = { message: e };
FB.api('/' + id, 'POST', edit, function (response) {
if (response && !response.error) {
var comment = $('#comment-message-' + id),
form = $('#edit-comment-form-' + id); // forgot to add '#' here
comment.removeChild(form);
comment.html('<div id="comment-message-' + id + '">' + e + '</div>');
}
});
}
【问题讨论】:
-
您应该为此使用 contenteditable。这样,您只需添加和删除 contenteditable 属性即可更改模式。
-
@firefoxuser_1 感谢您的想法。不幸的是,
contenteditable没有给用户明确的指示,告诉他们可以编辑我需要的文本。 -
@JustinWhite 检查我的答案
标签: javascript jquery html