首页 > 解决方案 > removeAttribute 不适用于数组中的最后一个元素

问题描述

我有一个元素数组,用于使用 JQuery 搜索相应的 HTML,然后我需要从中删除属性。我的功能如下所示:

for (const block of collection) {
            //selectedBlock is returned as an array that I only want the first element of
            const selectedBlock = $('g').find(`[data-type='` + block.attributes.type + `']`)[0];
            selectedBlock.removeAttribute('pointer-events');
            selectedBlock.removeAttribute('opacity');
}

该代码适用于数组中除最后一个元素之外的每个元素。我试过调试它,它运行得很好,但删除的属性之后仍然存在。如果我通过运行循环 collection.length+1 次来强制出现越界错误,它会起作用,但随后会出现越界错误。尽管代码正常执行,为什么函数不会影响最后一个元素?

编辑:

我用我正在尝试做的所有基本组件制作了一个 jsfiddle https://jsfiddle.net/1w04y6kr/4/(一些带有属性 data-type/pointer-events/opacity 的 <g>s,还有一些代码来查找每种数据类型中的第一个并删除属性)。此示例 100% 有效,但在我的项目中也有相同的逻辑,它仍然只是没有从最后一个元素中删除指针事件/不透明度collection

更新

@Wimanicesir 是正确的,问题出在项目中的其他地方(一个看似不相关的区域,也必须对此进行调查),在执行上述代码后将属性添加回最后一个元素。一个简单的函数重新排序修复了它。

标签: javascriptjquery

解决方案


尝试不同的方法。像这样使用 HTML / SVG / XML:

<g data-type='type1' pointer-events='none' opacity='0.8'>Example 1</g>
<g data-type='type2' pointer-events='none' opacity='0.8'>Example 1</g>
<g data-type='type1' pointer-events='none' opacity='0.8'>Example 1</g>
const collection = ['type1', 'type2'];

collection.forEach(blockType =>
  $(`g[data-type="${blockType}"]`)
    .removeAttr('pointer-events')
    .removeAttr('opacity')
);

通常在 HTML 中,pointer-events并且opacity是 CSS,而不是 HTML 属性。如果是这样,请使用:

collection.forEach(blockType =>
  $(`g[data-type="${blockType}"]`).css({
    'pointer-events': 'initial',
    'opacity': 'initial',
  })
);

推荐阅读