我已经把一个应用程序,利用Typeahead.js和包含美国各州一个选择框的。
由于文档显示,库中有remote财产。
我想补充我的选择框来remote
所选选项的值:
var chooseState = function() {
var jud = '',
stateChoice = $('.cm-state').find('option:selected'),
stateText = stateChoice.text(),
jud = stateChoice.val();
console.log(jud);
if (jud == '') {
$('#display').hide();
} else {
$('#display').fadeIn(150);
}
$('#choice span').text(stateText);
$('#choiceVal span').text(jud);
}
$('.cm-state').on('change', chooseState);
$('input.typeahead').typeahead({
name: 'typeahead',
remote: 'search.php?key=%query&jud=' + jud,
limit: 11,
// My addition
complete: chooseState
});
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="typeahead" type="text" placeholder="Choose State">
</div>
<div>
<select class="cm-state">
<option value="">- Choose state -</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="CA">California</option>
</select>
</div>
<div id="display">
<p id="choice">State name: <span></span></p>
<p id="choiceVal">State code: <span></span></p>
</div>
我得到一个犹没有定义错误消息来代替。
使得jud
可变全球与window.jud = stateChoice.val();
没有任何解决问题。
我在想什么?
首先,你应该取jQuery
之前,从CDN获取typeahead
其次,您声明jud
变量chooseState
函数内部,从而它不能从上线typeahead
初始化函数访问20
,你写的$('input.typeahead').typeahead({
检查下面的代码片段。
var jud = ''; // declare 'jud' variable here, so it's global in the first place;
var chooseState = function() {
// don't declare 'jud' here as it will become local variable for chooseSate function only;
var stateChoice = $('.cm-state').find('option:selected'),
stateText = stateChoice.text();
// seperate jud from var declaration now, just update the global one;
jud = stateChoice.val();
console.log(jud);
if (jud == '') {
$('#display').hide();
} else {
$('#display').fadeIn(150);
}
$('#choice span').text(stateText);
$('#choiceVal span').text(jud);
}
$('.cm-state').on('change', chooseState);
$('input.typeahead').typeahead({
name: 'typeahead',
remote: 'search.php?key=%query&jud=' + jud,
limit: 11,
// My addition
complete: chooseState
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- jQuery first, and then typeahead -->
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<div>
<input class="typeahead" type="text" placeholder="Choose State">
</div>
<div>
<select class="cm-state">
<option value="">- Choose state -</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="CA">California</option>
</select>
</div>
<div id="display">
<p id="choice">State name: <span></span></p>
<p id="choiceVal">State code: <span></span></p>
</div>