You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery获取td内contenteditable span输入值返回空字符串问题

问题现象

需要获取表格<td>标签内,用户通过contenteditable属性编辑修改的span元素内容,先后尝试两种取值写法,变量均返回空字符串,无法获取用户实际输入的内容:

let newItemName = $(variantId).children(".item-description").text();
let newItemName = $(variantId).find('span.item-description').text();

涉及的原有JS代码:

let variantId;
$(document).on('click', ".tbl-itemClass", function () {
    variantId = $(this).attr('id');
    $(variantId).prop('contenteditable', true);

}).
    on('input', function () {
        //let newItemName = $(variantId).children(".item-description").text();
        let newItemName = $(variantId).find('span.item-description').text();
    });

涉及的.cshtml(Asp.Net Razor Pages)代码:

<tbody>
@foreach (var item in Model)
{
    <tr currentitemid=" @item.Id">
        <td class="tbl-itemClass desc" id="@("description"+ item.Id)" varianttype="@ViewBag.VariantType" >
            <span class="spnSpc">&nbsp;&nbsp;&nbsp;</span>
            <span style="width:90%; padding:1px 5px 1px 2px;" class="item-description" contenteditable> @item.Description </span>
        </td>
        
        <td class="tbl-itemClass ">//more code here
        </td>
    </tr>
}

初始状态下@item.Description为颜色值(例如red),用户修改为其他值(例如redX)时,上述取值代码返回空字符串,无法获取修改后的实际值。

问题根因
  • 核心错误:jQuery id选择器格式错误。从DOM属性拿到的variantId是类似description123的纯id字符串,直接写$(variantId)会匹配标签名为description123的元素,根本无法定位到目标td节点,空jQuery对象调用.text()自然返回空字符串。正确的id选择器必须带#前缀,即$('#' + variantId)。
  • 逻辑错误:input事件全局绑定在document上,没有限定触发源,页面任意位置触发input事件都会执行取值逻辑,若此时variantId未赋值或值不匹配,也会导致取值失败。
  • 冗余配置错误:实际可编辑的是内层span.item-description元素,本身已经添加了contenteditable属性,额外给外层td设置contenteditable=true会导致编辑焦点混乱。
  • 细节问题:Razor模板中span标签和@item.Description变量之间存在多余空格,会导致初始文本前后带空白字符,取值时容易出现多余字符干扰。
修复方案
  1. 移除给外层td设置contenteditable的冗余逻辑,避免焦点冲突
  2. 直接将input事件绑定到实际可编辑的span.item-description元素上,不需要全局监听,也不需要额外定义全局变量存储id,事件回调中直接通过$(this)获取当前编辑元素即可
  3. 取值时增加.trim()清理前后多余空白字符

修复后的JS代码参考:

// 点击单元格时自动聚焦到内部可编辑span,优化交互
$(document).on('click', ".tbl-itemClass", function () {
    $(this).find('span.item-description').focus();
});

// 直接监听可编辑span的输入事件
$(document).on('input', 'span.item-description', function () {
    // 实时获取编辑后的内容,trim清理多余空白
    let newItemName = $(this).text().trim();
    console.log('编辑后内容:', newItemName);

    // 若需要获取当前行关联的item id,可通过向上查找tr节点获取属性
    // let currentItemId = $(this).closest('tr').attr('currentitemid').trim();
});

内容的提问来源于stack exchange,提问作者M Wel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 08:18:35