2017-06-03 57 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());

})。

相關問題