当选择框中的值被选中时,我尝试调用一个函数。我还会选择一个默认值,并在页面上为该值显示一个按钮。
这是我的选择框:
<select id="messagingMode" class="bootstrap-select" >
<option value="1" selected="selected">Webhooks messaging</option>
<option value="2">Real time messaging</option>
</select>这是js:
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn(this));并且该函数只打印当前选定的值:
function showCorrespondingAuthorizationBtn(select) {
console.log(select.val());
}控制台没有打印任何东西,为什么这个不起作用?
发布于 2017-06-03 16:57:46
尝试使用更改函数中的直接调用function name,而不是使用function() .Default绑定this
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn);
function showCorrespondingAuthorizationBtn() {
console.log($(this).val());
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="messagingMode" class="bootstrap-select">
<option value="1" selected="selected">Webhooks messaging</option>
<option value="2">Real time messaging</option>
</select>
发布于 2017-06-03 16:55:10
您正在调用函数,而不是将其作为引用传递。此外,在这种情况下,this并不是您所认为的那样。
尝试:
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn);
function showCorrespondingAuthorizationBtn(event) {
console.log($(this).val());
// or
console.log(this.value);
}发布于 2017-06-03 17:01:01
使用jQuery事件委派:
$('#messagingMode').on('change',function(){
console.log($(this).val());
});Here是一个有效的小提琴。
https://stackoverflow.com/questions/44342129
复制相似问题