简体   繁体   English

为什么element.attribute在Edge中不起作用?

[英]why doesn't element.attribute doesn't work in Edge?

I'm creating a small quiz type application in javascript. 我正在用javascript创建一个小的测验类型的应用程序。 My html structure looks like this. 我的html结构如下所示。

<div class="btn-group-toggle" data-toggle="buttons">
  <label class="btn btn-secondary btn-insight" data-target="#myCarousel" data-responseID="1">
  <input type="radio" name="options" id="option1" autocomplete="off"> 
  <h5>1</h5> 
  <p class="mb-0">label for 1</p>
  <div class="line-bottom gradient-purple"></div>
</label>
...
</div>

I'm trying to use the custom data attribute data-responseID to determine what answer was provided by the user. 我正在尝试使用自定义数据属性data-responseID来确定用户提供了什么答案。

When the program starts, loop through the labels using querySelectorAll and attaching a click listener to each one. 程序启动时,使用querySelectorAll遍历标签,并在每个标签上附加一个Click侦听器。

const responseLables = document.querySelectorAll('div.btn-group-toggle > label');
responseLables.forEach(element => {
    element.addEventListener('click', function(e){
        const clickedResponse = element.attributes[2].value;
        determineWhereToSlide(clickedResponse);
    });
});

This works well in Firefox and Chrome, but doesn't in Edge. 这在Firefox和Chrome中很好用,但在Edge中则不行。 (I'm not concerned with IE 11) (我不关心IE 11)

determineWhereToSlide is just a function that gives an alert for now. defineWhereToSlide只是一个提供警报的函数。 Eventually it'll be used to push the carousel forward. 最终,它将被用来推动旋转木马前进。

I've made a working example and you can see the issue if you open it up in different browser. 我已经制作了一个有效的示例,如果您在其他浏览器中打开它,则可以看到该问题。

https://codepen.io/anon/pen/dLmQKZ?editors=1010 https://codepen.io/anon/pen/dLmQKZ?editors=1010

I don't get why this is happening. 我不知道为什么会这样。

*EDIT 1 *编辑1

I just realized that the order of the attributes are different. 我只是意识到属性的顺序是不同的。 If you change the index value to ...attributes[1]... then it works just fine. 如果将索引值更改为...attributes[1]...那么它就可以正常工作。 Is there a better way to do this rather than providing an index? 有没有比提供索引更好的方法呢?

You can use the getAttribute() method. 您可以使用getAttribute()方法。

replace this 取代这个

const clickedResponse = element.attributes[2].value;

to this 对此

const clickedResponse = element.getAttribute('data-responseID')

Don't refer to attributes by index (even if it seems it should work, attributes were unordered at least until DOM3). 不要按索引引用属性(即使看起来应该起作用, 至少在DOM3之前属性是无序的 )。 Use any of: 使用以下任何一种:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM