如何在onclick上编辑数据

问题描述:

我不确定它叫什么,但是我希望能够点击例如包含数字的div,然后它将变为输入文本字段,其值为我单击的数字.

I am not sure what it is called, but I want to be able to click on e.g. a div containing a number, and then it will change into a input text field, with the value being the number I clicked.

然后我要编辑该号码,然后单击关闭(onblur事件),它将从显示新的已编辑号码的文本字段更改回div.该数字也将通过ajax更新到数据库中.

Then I want to edit the number, and click off (onblur event), and it will change back to a div, from the text field showing the new edited number. The number would have also been updated into the database via ajax.

此函数叫什么?
最好的编码方式是什么?

What is this function called?
What is the best way to code this?

您可以执行以下操作:

发生点击事件并动态创建一个文本框,该文本框将div中的文本作为值.

Have a click event and create a textbox on the fly which takes the text inside the div as a value.

具有模糊效果,甚至会绑定到该文本框并进行AJAX调用,并成功更改div文本

The have a blur even which binds to that textbox and makes an AJAX call and in its success change the div text

让我们说您的HTML就像:

Lets say your HTML is like:

<div id="fullname">Amazing Spider man</div>

您的JS代码如下:

$('#fullname').click(function(){
    var name = $(this).text();
    $(this).html('');
    $('<input></input>')
        .attr({
            'type': 'text',
            'name': 'fname',
            'id': 'txt_fullname',
            'size': '30',
            'value': name
        })
        .appendTo('#fullname');
    $('#txt_fullname').focus();
});

$(document).on('blur','#txt_fullname', function(){
    var name = $(this).val();
    $.ajax({
      type: 'post',
      url: 'change-name.xhr?name=' + name,
      success: function(){
        $('#fullname').text(name);
      }
    });
});

在此 jsfiddle