Linking to other page based on datalist option

别说谁变了你拦得住时间么 提交于 2021-02-07 20:12:55

问题


Now I have a datalist with a few options, and I want to link to other page when one of them is selected. Below is my first attempt, in which I tried to directly add a hyper link to the option label. But it did not seem to work.

    <input type="text" name="my-input" list="my-list">
    <datalist id="my-list">
    <option value="a"><a href="http://stackoverflow.com/questions"></a>a</option>
    <option value="b"><a href="http://stackoverflow.com/questions"></a>b</option>
    <option value="c"><a href="http://stackoverflow.com/questions"></a>c</option>
    </datalist>

Then I also tried to specify the onclick event of each option, and jump to other page accordingly, but still failed. So is it possible to achieve this using datalist?


回答1:


This is how I would do it:

$(document).ready(function() {
  $("[list='my-list']").on("input propertychange", function() {
    window.location = $("#my-list option[value='"+$("[list='my-list']").val()+"']").find("a").attr("href")
  });
});

Here is the CodePen demo

Note that the page is blank after redirect because SO does not allow cross domain origin. Check your console to see the redirect attempt.



来源:https://stackoverflow.com/questions/43407639/linking-to-other-page-based-on-datalist-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!