【问题标题】:(click) event not working on Chrome over select's option - Angular 12(点击)事件在选择的选项上无法在 Chrome 上运行 - Angular 12
【发布时间】:2021-11-02 12:29:59
【问题描述】:

我有一个选择输入,我需要将可迭代项的索引作为参数发送,因此在选择上使用(更改)事件对我不起作用。我必须在选项标签上使用(单击)事件,它适用于 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 中会发生这种情况以及如何解决它?

【问题讨论】:

  • 当然您可以发送带有更改事件的索引。不要使用点击选项标签,这没有意义
  • 索引“j”在选择标签上不存在,j 索引存在直到读取选项标签。所以javascript会抛出一个错误:“j is undefined”。无论如何我需要帮助,所以如果你有这个工作的答案,如果你能与我分享,我会感谢你。

标签: angular google-chrome select click option


【解决方案1】:

使用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>

就个人而言,我不明白为什么需要这样做,因为您可以只获取 select 的值并根据实际值进行操作。

【讨论】:

    猜你喜欢
    • 2013-03-11
    • 2018-02-06
    • 2010-11-26
    • 1970-01-01
    • 2015-07-14
    • 2017-03-08
    • 2021-11-11
    相关资源
    最近更新 更多