单击时将表格单元格从跨度更改为输入

我试图在单击时将表格单元格从“span”类型更改为“input”,然后在模糊处更改为“span”,但它不能像在此处给出的那样工作:

使用JQuery将表格单元格转换为文本框

这是javascript代码:

 $(document).ready(function() { $('#assets').click(function () { $('tr td:nth-child(3)').each(function () { var html = $(this).html(); var input = $(''); input.val(html); $(this).html(input); }); }); });  

这是文件正文

  
Name ast1 Location Loc-1
Name ast2 Location Loc-2

使用jQuery 1.7.2

这有什么不对? 请帮忙 !

谢谢!!

更新:只需要使用class =’asset_value’更改单元格,并且一次只能更改一个单元格。 此外,它应该改变回模糊的跨度..

试试这个 :

 $(document).ready(function() { $('#assets').on('click', 'span', function() { var $e = $(this).parent(); if($e.attr('class') === 'asset_value') { var val = $(this).html(); $e.html(''); var $newE = $e.find('input'); $newE.focus(); } $newE.on('blur', function() { $(this).parent().html(''+$(this).val()+''); }); }); });​ 

这将在点击时更改单个单元格并在模糊时恢复为跨度。

您可以使用replaceWith()方法, html()方法清空所选元素并向其添加html标记,请尝试以下操作:

  $(document).ready(function() { $('#assets').click(function () { $('tr td:nth-child(3)').each(function () { var html = $(this).html(); var input = $(''); input.val(html); $(this).replaceWith(input); }); }); }); 

DEMO


由于replaceWith方法更改了标记的结构,您应该为生成的标记委派事件,您可以使用on方法,尝试以下操作:

  $(document).ready(function() { $(document).on('click', '#assets td', function () { var html = $(this).text() var input = $(''); input.val(html); $(this).replaceWith(input); $('#assets input').focus(); }); $(document).on('blur', '#assets input', function(){ $(this).replaceWith(''+this.value+'') }) }); 

DEMO

希望这会对你有所帮助: http : //jsfiddle.net/RBGME/19/

HTML:

 
Name ast1 Location Loc-1
Name ast2 Location Loc-2

CSS示例:

 td { border: 1px solid #aaa; height: 30px; text-align: center; width: 100px; } input, input:hover, input:focus { width: 100px; height: 30px; box-sizing: border-box; outline: none; background-color: #eee; } 

jQuery的:

 $(document).ready(function() { $('#assets tr td:nth-child(3)').click(function () { var html = $(this).html(); var input = $(''); input.val(html); $(this).replaceWith(input); }); });? 

我认为你是正确的方式试试这个:

 $(document).ready(function() { $('#assets').click(function () { $(this).find("span").replaceWith(input); }); }); 
 $('td').click(function(){ $(this).children('span').html(''); })