问题
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