0

我正在尝试制作可编辑的文本。我所拥有的是您单击的一行文本,我需要出现一个文本框,允许用户更改文本的值。使用我拥有的代码,当您单击时,文本会消失。有任何想法吗?html

       <div class="test">Click here</div>

jQuery

       $(".test").click(function() {
           var inputValue = $(".test").text();  
           $(".test").html("<input value='"+inputValue+"' 
               type='text' id='box1'>");
           $("#box1").val(inputValue).select();
        });
4

3 回答 3

1

如果您将使用现有的解决方案,也许会更简单。例如:可编辑

但如果你想(见演示):

$(document).ready(function () {
    var beginEdit = function () {
        var text = $(this).text();
        var input = $('<input value="' + text + '" type="text">').one('blur', endEdit);

        $(this).empty().append(input);
    };

    var endEdit = function () {
        var text = $(this).val();
        $(this).parent().html(text).one('click', beginEdit);
    };

    $(".text").one('click', beginEdit);
});​

作为 jQuery 的插件(参见DEMO2):

$.fn.editable = function () {
    this.each(function () {    
        var beginEdit = function () {
            var text = $(this).text();
            var input = $('<input value="' + text + '" type="text">').one('blur', endEdit);

            $(this).empty().append(input);
        };

        var endEdit = function () {
            var text = $(this).val();
            $(this).parent().html(text).one('click', beginEdit);
        };

        $(this).one('click', beginEdit);        
    });
};

$(document).ready(function () {
    $(".text").editable();
});​
于 2012-07-31T15:38:31.553 回答
0

This jsFiddle has an example. When you click a paragraph, the jQuery event handler replaces the HTML in the paragraph with a text box containing the text of the paragraph.

When you click the newly-created text box, the text in it disappears. This is because the event handler fires again when you click the text box: the HTML of the paragraph (the text box) is replaced with a text box containing the text of the paragraph. There's no text, so now you get a new empty text box.

There's a few ways you could stop this happening. When you create the text box, you could change the class of the paragraph, meaning your event handling code would no longer fire. Or, you could have another handler for the click event of the text boxes, and in here call the stopPropagation function.

于 2012-07-31T15:46:37.727 回答
0

拿走线$("#box1").val(inputValue).select();。您已经在html()方法中设置了值。此外,在调试器中检查 inputValue 是否有值。

格雷厄姆指出的是,当你点击它时,它会变成

<div class="test"><input value="Click here" type="text" id="box1"></div>

单击事件仍在外部 div 上,因此当您再次单击它时,它会清除文本框。

于 2012-07-31T15:44:47.733 回答