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

Mac版Chrome中JavaScript动态添加的onfocus事件不触发如何解决

问题现象

仅在OSX 12.4系统运行的Chrome 103.0.5060.114(Official Build,x86_64架构)版本中存在异常:通过JavaScript动态添加的onFocus事件无法触发。

  • 同页面的该事件在iOS端Chrome、其余版本、其余品牌浏览器中均可正常触发
  • 若将事件以内联写法直接写入HTML标签,在上述异常版本OSX端Chrome中也可正常执行
复现代码
let lblP = document.createElement('label');

let inpDesc = document.createElement('input');
        inpDesc.type = "text";
        inpDesc.className = "input_Text  marginLeft holdStatus"; 
        inpDesc.size="115";
        inpDesc.id = "holdcremation_description_" + newRow.rowIndex;
        inpDesc.name = "holdcremation_description_" + newRow.rowIndex;
        inpDesc.value = "";
        
        descID = inpDesc.id;
        //will need sync and array update
        inpDesc.onfocusout=function() {
            
            updateArrayOnClick('holdeventsstatus_List', 'holdeventsstatus_List', this.id, 'description', this.value);
            //updateSureMap(this.id, this.value, '');
            };
            
        lblP.appendChild(inpDesc);
故障原因

该版本Chrome x86_64版本存在已知渲染bug:动态创建的DOM元素,通过直接赋值DOM0级事件属性(即element.onxxx = function(){}写法)注册的焦点类事件(focus/focusout/blur),不会被正确挂载到元素的事件监听队列,因此无法正常触发。内联写在HTML中的事件在HTML解析阶段就完成注册,不会触发该bug。

修复方案

弃用DOM0级事件赋值写法,使用W3C标准的addEventListener方法注册焦点事件即可兼容所有浏览器环境,该写法在上述异常版本Chrome中可正常触发事件。
以原代码中的focusout事件为例,修正后的事件绑定代码如下:

// 替换原有的inpDesc.onfocusout = function() {} 写法
inpDesc.addEventListener('focusout', function() {
  updateArrayOnClick('holdeventsstatus_List', 'holdeventsstatus_List', this.id, 'description', this.value);
  //updateSureMap(this.id, this.value, '');
}, false);

如果需要绑定focus事件,同理使用inpDesc.addEventListener('focus', 对应处理函数, false)写法即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 11:27:22