【问题标题】:Replacing input with div, after replacing div with input将 div 替换为 input 后​​,将 input 替换为 div
【发布时间】: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


【解决方案1】:

使用下面的代码将输入类型替换为 div

FB.api('/' + id, 'POST', edit, function (response) {
    if (response && !response.error) {
        $('#edit-comment-form-' + id).replaceWith('<div id="comment-message-' + id + '">' + e + '</div>')
    }
});  

您已经将 $('#comment-message-' + id) 替换为输入表单,所以同样需要将 $('#edit-comment-form-' + id) 替换为 $('#comment-message -' + id)

【讨论】:

  • 该死的,我昨晚试过了,但肯定是那里有错字。谢谢,它有效!
  • @JustinWhite 很乐意为您提供帮助 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-10
  • 2016-03-13
  • 1970-01-01
  • 2017-09-24
  • 2015-10-25
  • 1970-01-01
相关资源
最近更新 更多