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

如何递归搜索Canvas元素以获取含_dummy标识的按钮?

问题分析与解决方案

原函数报错原因

你之前的函数在处理<canvas> DOM元素时报错,核心原因是:原生HTML Canvas元素的children属性是HTMLCollection(类数组对象),并非标准的Array,所以没有forEach方法,直接调用就会抛出类型错误。而你之前处理的form、div等元素,虽然它们的children也是HTMLCollection,但部分现代浏览器对其做了兼容支持,或者你之前传入的是jQuery包装后的对象(jQuery对象的children()方法返回的是可遍历的jQuery集合),所以没报错。

你的新函数存在的问题

你用canvas.each()遍历jQuery选中的Canvas元素,但逻辑里的element.children instanceof Array判断永远为false(因为DOM元素的children是HTMLCollection,不是Array),导致递归分支永远不会触发,无法遍历嵌套的子元素,只能处理最外层元素的直接子节点,逻辑不完整。

正确的遍历实现方式

根据你的需求(找到名称带_dummy标识的按钮),分两种场景给出实现:

场景1:遍历Canvas标签内的DOM子元素

如果你的按钮是嵌套在<canvas>标签内的DOM元素(比如<canvas><button name="btn_dummy">...</button></canvas>),需要把HTMLCollection转为标准数组后再递归遍历:

function FindNestedDummyButtons(obj) {
  // 将HTMLCollection转为可遍历的数组
  const childElements = Array.from(obj.children);
  
  childElements.forEach(subObj => {
    // 递归遍历子元素的子节点
    if (subObj.children.length > 0) {
      FindNestedDummyButtons(subObj);
    }
    
    // 检查当前元素的父节点是否包含_dummy标识
    if (subObj.parent && subObj.parent.name.includes("_dummy")) {
      // 执行你的处理逻辑
      RegisterMovieClipAsBasicButton(subObj.parent);
    }
  });
}

// 使用示例:传入原生Canvas DOM元素
const canvasElement = $('canvas')[0];
FindNestedDummyButtons(canvasElement);

场景2:遍历Canvas绘图库的显示对象(如CreateJS的MovieClip)

如果你的“按钮”是Canvas画布上绘制的动画对象(比如用CreateJS等库创建的MovieClip),那你需要传入的是绘图库的显示对象实例(而非DOM元素),这类对象的children本身就是数组,可以直接递归遍历:

function FindNestedDummyMovieClips(displayObj) {
  displayObj.children.forEach(subObj => {
    // 递归遍历子显示对象
    if (subObj.children.length > 0) {
      FindNestedDummyMovieClips(subObj);
    }
    
    // 检查父显示对象的名称是否带_dummy
    if (subObj.parent && subObj.parent.name.includes("_dummy")) {
      RegisterMovieClipAsBasicButton(subObj.parent);
    }
  });
}

// 使用示例:传入CreateJS的Stage或MovieClip实例
// const stage = new createjs.Stage("canvasId");
// FindNestedDummyMovieClips(stage);

额外提示

  • 如果你用jQuery操作DOM,也可以直接用jQuery的find()方法简化遍历:$('canvas').find('[name*="_dummy"]'),直接选中所有名称包含_dummy的元素,无需手动递归(仅适用于DOM元素场景)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:48:08