首页 > 解决方案 > (点击)事件在选择的选项上无法在 Chrome 上运行 - Angular 12

问题描述

我有一个选择输入,我需要将可迭代项的索引作为参数发送,因此在选择上使用(更改)事件对我不起作用。我必须在选项标签上使用(单击)事件,它适用于 FF,但不适用于 chrome。

代码:

<select class="text-sm">
  <option value="" selected disabled>--</option>
  <option *ngFor="let option of item.opciones; let j = index" 
          value="{{ option.id }}"
          (click)="updateItemsList(i, $event, j)">
    {{ option.descripcion }}
  </option>
</select>

如您所见,如果我在 select 上使用 (change),则无法将 j 索引作为方法中的参数发送。

有人知道为什么在 chrome 中会发生这种情况以及如何解决它?

标签: angulargoogle-chromeselectclickoption

解决方案


使用selectedIndex,您可以访问所选选项的索引。

示例(从链接的 MDN 站点复制粘贴):

var selectElem = document.getElementById('select')
var pElem = document.getElementById('p')

// When a new <option> is selected
selectElem.addEventListener('change', function() {
  var index = selectElem.selectedIndex;
  // Add that data to the <p>
  pElem.innerHTML = 'selectedIndex: ' + index;
})
<p id="p">selectedIndex: 0</p>

<select id="select">
  <option selected>Option A</option>
  <option>Option B</option>
  <option>Option C</option>
  <option>Option D</option>
  <option>Option E</option>
</select>

就个人而言,我不明白为什么需要这样做,因为您可以获得选择的值并根据实际值采取行动。


推荐阅读