[英]why does input.value is returning undefined when call it in alert
我有一個文本輸入,我想在按回車鍵后提醒 input.value
所以我做了這個代碼 HTML:
<input type="text" id="food">
js:
$('#food').on('keypress',function(e) {
if(e.which == 13) {
const food = $('#food').value;
alert(food);
}
});
在警報中,它顯示undefined
。 另外,控制台沒有console error
您應該使用val()
方法來獲取 jquery 中輸入的值
$('#food').val()
value
在 vanilla JS 中使用,而不是在 jquery 中。
$('#food').on('keypress', function(e) { if (e.which == 13) { const food = $('#food').val(); console.log(food); // alert( food ); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id="food">
您需要在 jQuery 上使用 function 來獲取該值。
$('#food').val();
$('#food').attr('value');
它不是const food = $("#food").value
而是const food = $("#food").val()
在 jquery 你應該使用 .val() 來獲取字段的值 insted of.value
`const food = $('#food').val();`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.