我想將其添加到輸入字段,因此每當用戶鍵入或粘貼某些內容時,網頁上都會顯示一條警報。不過,這並不火(「代碼」是inputfield的id):Jquery輸入事件不會觸發
var codeInput = document.getElementById('code');
$('#code').on('input', function() {
window.alert(codeInput.value);
});
我想將其添加到輸入字段,因此每當用戶鍵入或粘貼某些內容時,網頁上都會顯示一條警報。不過,這並不火(「代碼」是inputfield的id):Jquery輸入事件不會觸發
var codeInput = document.getElementById('code');
$('#code').on('input', function() {
window.alert(codeInput.value);
});
假設你的HTML是確定的,這將工作:
$('#code').on('input', function() {
alert($(this).val())
});
我說假設,因爲如果HTML動態你可能需要一個不同的方法,像這樣:
$(document).on('input', '#code', function() {
alert($(this).val())
});
var codeInput = document.getElementById('code');
該行在執行JavaScript時遇到,將獲得對id爲code
的元素的引用,並將其存儲在codeInput中。這個值一旦被賦值就不會更新。
$('#code').on('input', function() {
window.alert(codeInput.value);
});
這是一個事件處理程序。在它被註冊一次之後,它將在每次元素code
都有輸入時執行。
但您試圖提醒codeInput
的值,該值已在和之前分配了值。
這應該工作(獲取參考元素的當前狀態,然後調用它的價值)
$('#code').on('input', function() {
alert($(this).val())
});
的jQuery沒有輸入事件時,您可以使用下面的代碼
var codeInput = document.getElementById('code');
$('#code').on('input', function() {
window.alert(codeInput.value);
});
你爲什麼混合js和jquery? '('input',function(){$(this).val()) }); ' –