給定一個數字輸入:
<input type="number" id="create-y-small" name="create-y-small" value="0">
如何以數字形式獲取輸入的值?以下回傳一個字串:
$("#create-y-small").val()
(附帶問題,為什么這是默認行為?當然應該期望數字型別輸入給出數字?)
我在別處尋找答案但沒有運氣:
輸入值是字串而不是數字 答案使用決議來決議為數字。我不想決議為數字,我只想將數字作為數字獲取。
從輸入數字中獲取變數值 OP 似乎很樂意將值作為字串獲取
在 jQuery 中獲取輸入數字的值 相同的故事
https://www.codegrepper.com/code-examples/javascript/how to get the value of input number using jquery 相同的故事
uj5u.com熱心網友回復:
html 中的所有輸入元素都回傳字串作為它們的值。如果你想要 int 的結果,你必須轉換它。
parseInt($("#create-y-small").val())
uj5u.com熱心網友回復:
您可以使用 jqueryvalHooks來更改 jquery 回傳值的方式。
$.valHooks.number = {
get: function( elem ) {
return elem.value * 1;
}
};
您只需要在代碼中執行一次此操作,然后所有type=number輸入都將回傳一個數字。
console.log(
"num is a string",
$("#num").val() === "1",
$("#num").val() === 1,
$("#txt").val() === "1",
$("#txt").val() === 1)
$.valHooks.number = {
get: function( elem ) {
return elem.value * 1;
}
};
// confirm no neffect on type='text'
console.log(
"num is a number",
$("#num").val() === "1",
$("#num").val() === 1,
$("#txt").val() === "1",
$("#txt").val() === 1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id='num' value="1">
<input type='text' id='txt' value="1">
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/368411.html
標籤:javascript 查询 html 输入元素
