【问题标题】:How to get notified when an <option selected> gets reselected?当 <option selected> 被重新选择时如何得到通知?
【发布时间】:2016-05-16 01:09:16
【问题描述】:

请参阅下面的代码。这是移动网站的导航。选择一个类别会加载所选类别页面,其中列出了该类别中的所有产品。 (例如,选择 Fruits 会加载 /fruits 类别页面,其中列出了指向苹果、香蕉、橙子等的链接。)查看产品页面时,&lt;select&gt; 中仅显示类别名称,而不是产品名称。我希望通过选择水果可以从苹果产品页面返回水果类别列表。但由于它已经被选中,change 事件不会被触发。我还能如何获得有关此操作的通知(当当前选定的项目未更改但再次选择时)?

<select onchange="location.href = event.target.options[event.target.selectedIndex].getAttribute('data-href');">
    <option data-href="/vegetables">Vegetables
    <option data-href="/fruits" selected>Fruits
</select>

【问题讨论】:

  • 也许是blur
  • 不幸的是,&lt;select&gt; 在选择项目时不会模糊。幸运的是,正如您在我的回答中看到的那样,我已经找到了一种解决方法。

标签: javascript drop-down-menu onchange


【解决方案1】:

我不知道这样的事件,但这个技巧非常有效。当前类别应再次添加到&lt;select&gt;,作为隐藏选项。将其选中而不是可见的,这样即使在选择当前类别时也会触发 change 事件。

<select onchange="location.href = event.target.options[event.target.selectedIndex].getAttribute('data-href');">
    <option hidden selected>Fruits
    <option data-href="/vegetables">Vegetables
    <option data-href="/fruits">Fruits
</select>

【讨论】:

    猜你喜欢
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多