我已经构建了一个样式的下拉列表并使用了无序列表。
数组中的项目将填充到选择下拉列表和ul下拉列表中。
用户选择一个项目,它会更新到目标范围,以及在选项中被选中。
然而,由于这一切都是通过js完成的,因此无法实际触发select的on change事件(据我所知)。
有没有办法将它绑定到我的其他功能?
这是html:
<div class="selectWrapper">
<select id="townResult" class="dropdown" name="townSelect">
<option disabled="" selected="" value="0">SELECT AN AREA</option>
<option value="Second">Second</option>
<option value="Third">Third</option>
</select>
<span class="selected">Selected option</span>
<ul class="townList"></ul>
</div>
JS / jQuery:
var popUkTowns = "[ FEATHERSTONE TOWN, ABARDARE, ABBEYDLE, ABBEYMEAD, ABBEYTOWN, ABBOTS LANGLEY, ABEDEEN, ABERAERON, ABERAMAN, ABERBARGOED, ABERCARN, ABERCHIRDER, ABERCYNON, ABERDARE, ABERDEEN, ABERDEENSHIRE, ABERDOUR, ABERDOVEY, ABERFAN, ABERFELDY, ABERFIELDY, ABERFOYLE, ABERGAVENNY, ABERGELE, ABERGELE CLWYD, ABERLOUR, ABERSOCH, ABERTILLERY, ABERTRIDWR, ABERYSTWTH, ABERYSTWYTH, ABINGDON, ABOYNE, ABRIDGE, ABROATH, ACCRINGTON, ACHARACLE, ACKLAM, ACKWORTH]";
popUkTowns = popUkTowns.split("[ ").join(",").split("]").join('"').split(",");
var townList = $('.townList');
var townResult = $('#townResult');
for(var i=0;i<popUkTowns.length;i++){
townList.append('<li>' + popUkTowns[i] + '</li>');
//townResult.append('<option value="' +popUkTowns[i]+ '">' +popUkTowns[i]+ '</option');
}
selectOption = function(){
var trigger = $('.selected');
trigger.on('click',function(){
$(this).parent().toggleClass('open');
return false;
});
var selectLI = townList.find('li');
selectLI.on('click',function(){
var thisLI = $(this).text();
townResult.empty();
townResult.append('<option value="' +thisLI+ '" selected="selected">' +thisLI+ '</option>');
trigger.html(thisLI);
var selectWrapper = $('.selectWrapper');
selectWrapper.removeClass('open');
});
}();
townResult.on('change',function(){
console.log('Value changed'); // this doesn't work of course
});
我有一个工作js小提琴here。通常选择将被隐藏,但是为了本练习的目的,我在小提琴中显示它以证明值在select选项中被更新。
我试图将一个on change事件绑定到该选项以及绑定selectOption
函数,但我似乎无法触发它,但可能有更好的方法来执行此操作(即当{ {1}}已更新)。
答案 0 :(得分:1)