1

我已经对该主题进行了一些谷歌搜索,但由于浏览器对 datalist 元素的支持仍然很差,似乎没有人使用它或者之前没有真正问过这个问题。我有一个数据列表:

<form>

     <input placeholder="Enter a location or choose from the list" list="restaurants" id="hp-restaurants">

     <datalist id="restaurants">
         <option value="Sanford, ME" data-attr="<?php echo site_url(); ?>/locations/weathervane-restaurants/sanford/" />
         <option value="Kitery, ME" data-attr="<?php echo site_url(); ?>/locations/weathervane-restaurants/kittery/" />
         <option value="Belfast, ME" data-attr="<?php echo site_url(); ?>/locations/lobster-in-the-rough/belfast/" />
         <option value="Waterville, ME" data-attr="<?php echo site_url(); ?>/locations/weathervane-restaurants/waterville/" />
         <option value="Brewer, ME" data-attr="<?php echo site_url(); ?>/locations/weathervane-restaurants/brewer/" />
         <option value="South Portland, ME" data-attr="<?php echo site_url(); ?>/locations/weathervane-restaurants/south-portland/" />
         <option value="Bedford, NH" data-attr="<?php echo site_url(); ?>/locations/weathervane-restaurants/bedford-nh/" />
         <option value="Dover, NH" data-attr="<?php echo site_url(); ?>/locations/weathervane-restaurants/dover-nh/" />
         <option value="Chichester, NH" data-attr="<?php echo site_url(); ?>/locations/weathervane-restaurants/chichester-nh/" />
         <option value="Salem, NH" data-attr="<?php echo site_url(); ?>/locations/weathervane-restaurants/salem-nh/" />
         <option value="West Lebanon, NH" data-attr="<?php echo site_url(); ?>/locations/weathervane-restaurants/west-lebanon-nh/" />
         <option value="Nashua, NH" data-attr="<?php echo site_url(); ?>/locations/weathervane-restaurants/nashua-nh/" />
     </datalist>

</form>

每个选项都应该链接到我在其中添加的 data-attr 属性中的页面。如果有更简单的方法可以让这些选项链接到页面,我只是不知道。这是我第一次尝试对 datalist 元素做任何事情。所以,如果我只是在根本上做错了,请随时带我去学校。

目前,我正在尝试在下拉列表更改时触发。我认为 jQuery 的 .change() 事件会处理这个问题,但事实并非如此。无论如何,我正在测试该事件以查看它是否会触发:

$('#hp-restaurants').click(function() {
    console.log('HELLO WORLD');
});

没有骰子。

在选项列表更改时,将此元素链接到这些页面有什么建议吗?

4

1 回答 1

6

If you're looking to fire an event when a datalist option has been selected, rather than waiting until the changeevent (which is fired when a new option has been selected and focus is given to another element) you should bind to the inputevent, like所以:

 $('#hp-restaurants').on('input', function () {
    console.log('Input has been changed.');
 });

jsFiddle 演示| 另请参阅 MDN 文档以获取“oninput”

于 2014-05-16T20:46:07.740 回答