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

jQuery如何使用.find()同时查找input或select标签获取单元格编辑值

解决方案

直接调整jQuery选择器的写法即可,jQuery的多标签选择器需要把多个标签名用逗号分隔,放在同一个字符串参数里,你之前的写法是给find传了两个参数,相当于限定搜索上下文为select,当然匹配不到结果。

具体修改

把原来的代码:

updValue=cell.find('input').val();

替换为:

updValue = cell.find('input, select').val();

就可以同时匹配单元格内的input或者select元素,自动拿到对应的值,完全不需要额外加class、name属性,符合你的轻量需求。


额外优化建议

你当前代码里的日期格式化判断存在bug:if(e.target.cellIndex==4) 这里的e.target是你点击表格外的元素,根本不会有cellIndex属性,永远不会触发日期格式转换逻辑。建议直接复用双击时已经存储的tdIndex变量来判断:

if(tdIndex == 4){
    let temp=updValue.split('-');
    updValue=temp[2]+'/'+temp[1]+'/'+temp[0];
}

修改后的完整代码

let editing = false;
let cell, tdIndex; // 把公共变量提到外层作用域,两个事件都可访问
tableCells.dblclick(function() {
    cell=$(this)
    value=cell.text();
    editing=true;
    rowIndex = cell.parent().index('table tbody tr');
    tdIndex = cell.index('table tbody tr:eq('+rowIndex+') td');
    switch(tdIndex) {
        case 1:
        case 2:
        case 9:
            cell.html('<input type="text" value="'+value+'">');
        break;
        case 3:
            cell.html('<select name="dob" id="dob" class="form-control"><option value="1">Uomo</option><option value="2">Donna</option></select>');
            break;
        case 4:
            let temp = value.split('/');
            value=temp[2]+'-'+temp[1]+'-'+temp[0];
            cell.html('<input type="date" value="'+value+'">');
        break;
    }
});
$(document).click(function(e) { //点击表格外区域触发保存
    if(editing){
        if (!tableCells.toArray().some(f => f.contains(e.target))) {
            let row = cell.parent('tr').data('row'); // 获取要更新到数据库的行标识
            updValue = cell.find('input, select').val();
            if(tdIndex==4){
                let temp=updValue.split('-');
                updValue=temp[2]+'/'+temp[1]+'/'+temp[0];
            }
            
            console.log(updValue);
            console.log('riga '+row);
            cell.html(updValue);
            editing = false;
        }

    }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:45:03