0

我正在使用车把模板引擎

<div class="input-wrapper col-md-12">
    <input id="{{#if type}}{{type}}{{else}}text{{/if}}" name="{{#if type}}{{type}}{{else}}text{{/if}}"
        class="input--default" type="{{#if type}}{{type}}{{else}}text{{/if}}" data-filled="false" {{{data-rules}}}
        {{{data-messages}}} data-input-type="{{#if type}}{{type}}{{else}}text{{/if}}"/>
    <label for="{{#if type}}{{type}}{{else}}text{{/if}}" class="o-input__label">
        {{#if label}}
        {{label}}
        {{else}}
        Label
        {{/if}}
    </label>
    <span class="input-icon__svg-wrapper" id="error-icon">
        <svg viewBox="0 0 18 18" class="input-icon__svg">
            <use xlink:href="{path-to-svg-file}#error"></use>
        </svg>
    </span>
    <span class="input-icon__svg-wrapper" id="password-icon">
        <svg viewBox="0 0 18 18" class="input-icon__svg" pointer-events="none">
            <use xlink:href="{path-to-svg-file}#password" pointer-events="none"></use>
        </svg>
    </span>
</div>
// This work
// PS: [5] is the password-icon span
document.querySelectorAll('.input-icon__svg-wrapper')[5].addEventListener('click', e => {
  console.log(e)
})

// This doesn't work
document.querySelector('#password-icon').addEventListener('click', e => {
  console.log(e)
})

任何人都可以向我解释这里有什么区别以及为什么一个有效而另一个无效。

另外,请告诉我是否有更好的方法来处理脚本。最好是跨文档脚本,而不是使用标签onclick上的属性svg/use

4

1 回答 1

0

因为我使用的是把手,所以我在这个模板上循环了 4 次。

我的目标是错误的元素,这就是为什么直接索引有效而不是其他方法的原因。显然我在NodeList运行时得到了一个数组:

document.querySelector('#password-icon').addEventListener('click', e => {
  console.log(e)
})

这让我意识到我没有正确定位元素访问器。

于 2020-04-01T11:00:11.753 回答