如何在onclick上编辑数据

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

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

这个函数叫什么?
编码的最佳方法是什么?

您可以执行以下操作:

有一个click事件并动态创建一个文本框,它将div中的文本作为值。

有一个模糊甚至绑定到该文本框并进行AJAX调用,并在其成功更改div文本

让我们说你的HTML就像:

 
Amazing Spider man

你的JS代码就像:

 $('#fullname').click(function(){ var name = $(this).text(); $(this).html(''); $('') .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中演示的

有jEditable: http : //www.appelsiini.net/projects/jeditable

但是,X-editable看起来更好: http : //vitalets.github.io/x-editable/

在此处输入图像描述

HTML5有一个contentEditable属性,具有非常好的浏览器支持,所以你可能想先探索它,特别是如果你想做no-jquery。 简单地将contentEditable="true"放入div中将使其可单击和可编辑(基本文本)。

要实际使用editable元素,您需要使用JS。 在JS中设置一个侦听器,以便在触发时执行操作。 在OP的情况下,他会将新编辑的内容放在某处(如数组),准备好将ajax函数发送到外部数据库。 更多信息在这里 。

此外, 这是一个插件 ,它进一步发展并为这些字段提供更多WYSIWYG控件。

无论如何,这是一个示例代码,没有插件,没有jquery:

 var myEditableElement = document.getElementById('myContent'); myEditableElement.addEventListener('input', function() { console.log('An edit input has been detected'); console.log(myEditableElement.innerHTML); }); 
 
This is an editable element. Click and type something!

它被称为jQuery编辑。 jQuery提供了许多插件。

为什么不保持一个输入字段,并在模糊时更改字段样式。 你可以把所有东西拿走,所以它看起来不像是输入,这样就不需要来回改变了。 在模糊时进行Ajax调用。

您已将整个过程命名为。

首先,将所有数字或字段分配给某个类。

 
value

然后,为该类分配一个click事件。

 $('.editable').click(function(){ //replace element with input element containing the value //attach an onblur event to the new element $(newelement).blur(function(){ //use $.ajax to send the element's value to your server //remove the input element and then replace the previous element with the new value }); });