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

如何在jQuery Datatables Editor模态框输入框中限制空格输入

问题原因分析
  • 选择器不匹配:目标输入框的ID为DTE_Field_re-re_netipaddress,你代码中使用的选择器ID为DTE_Field_remoteinstalltickets-remoteinstallticket_netipaddress,二者完全不一致,无法定位到目标元素。
  • 动态元素绑定失效:jQuery Datatable Editor的模态框属于动态生成元素,仅在触发新增/编辑操作时才会插入DOM树。你在$(document).ready阶段直接绑定事件时,目标元素还不存在,事件绑定不会生效。
正确实现方案

方案1:事件委托(无需依赖Editor实例)

将事件委托到页面已存在的上层元素(如document),后续动态生成的匹配选择器的元素会自动触发绑定的事件,同时覆盖手动输入、粘贴等所有可能输入空格的场景:

$(document).on({
  keydown: function(e) {
    if (e.which === 32) {
      e.preventDefault();
      return false;
    }
  },
  input: function() {
    this.value = this.value.replace(/\s/g, "");
  },
  paste: function(e) {
    const pastedText = e.originalEvent.clipboardData.getData('text');
    this.value = pastedText.replace(/\s/g, "");
    e.preventDefault();
  }
}, "input#DTE_Field_re-re_netipaddress");

方案2:Editor原生生命周期绑定(性能更优)

如果你的Editor实例已经声明(假设实例变量名为editor),可以利用Editor提供的open生命周期事件,在模态框打开、元素渲染完成后再绑定事件:

editor.on('open', function () {
  const $targetInput = $("input#DTE_Field_re-re_netipaddress");
  $targetInput.on({
    keydown: function(e) {
      if (e.which === 32) {
        e.preventDefault();
        return false;
      }
    },
    input: function() {
      this.value = this.value.replace(/\s/g, "");
    },
    paste: function(e) {
      const pastedText = e.originalEvent.clipboardData.getData('text');
      this.value = pastedText.replace(/\s/g, "");
      e.preventDefault();
    }
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:24:03