2017-06-03 59 views
1

我尝试从选择框中选择一个值时调用一个函数。我还会选择一个默认值,并在页面上显示该值。为什么选择更改方法不起作用?

这是我的选择框:

<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()); 
} 

没有什么打印在控制台中,为什么这不起作用?

回答

2

您正在调用该函数,而不是将其作为参考传递。 this也不是你认为它在这种情况下。

尝试:

$('#messagingMode').on('change',showCorrespondingAuthorizationBtn); 

function showCorrespondingAuthorizationBtn(event) { 
    console.log($(this).val()); 
    // or 
    console.log(this.value); 
} 
0

它不触发,因为你正在调用你的事件连接的逻辑方法。

// calling the invocation operator() triggers the method 
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn(this)); 

为了解决这个问题,请尝试下面的代码。

function onDropdownChanged() { 
    var sender = $(this); 
    console.log(sender.val()); 
} 

$(document).ready(function() { 
    $('#messagingMode').on("change", onDropdownChanged); 
}) 
3

尝试直接调用function namefunction() .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>

1

使用jQuery的事件代表团:

$('#messagingMode').on('change',function(){ 
    console.log($(this).val()); 
}); 

Here是一个工作小提琴。

1

$( '#messagingMode')改变(函数(){

showCorrespondingAuthorizationBtn($(本).VAL());

})。

相关问题