为什么我触发功能时输入类型=数字值为空

时间:2019-06-06 13:57:48

标签: javascript html

当我键入一个数字时,它会给我输入的第一个数字的e.code,如果我键入另一个数字,它会给我输入数字的e.code,但它的值是第一个数字值

   var input = document.getElementById('w-input');
        var kg = document.getElementById('kg');

        input.addEventListener('keypress', function (e) {
            if (e.code === 'Numpad1'|| e.code==='Numpad2'|| e.code==='Numpad3' || 
               e.code==='Numpad4'|| e.code==='Numpad5'|| e.code==='Numpad6'||
               e.code==='Numpad7'|| e.code==='Numpad8'|| e.code==='Numpad9'||  
               e.code==='Numpad0') {
                   console.log(e.code);
                   lbsToKg();
             }
   });

   function lbsToKg() {
    console.log(input.value);
    kg.innerHTML = input.value * 0.45359237;

   }

它应该获得输入值并将其与数字相乘,但不相乘得到1-9数字0表示该值为空。如果我输入12,则结果为0.45359237,这意味着它将乘以1而不是12

2 个答案:

答案 0 :(得分:1)

在输入更改值之前触发

keypress。使用keyup会在输入更改值后触发

function print(inp,e) {
    console.log(inp.value);
}
<input onkeypress="print(this,event)" placeholder='keypress'>
<input onkeyup="print(this,event)" placeholder='keyup'>

答案 1 :(得分:1)

Kamil回答了有关为什么值不正确的问题,但是您还可以减少检查按键的代码量,这可能会有用。

library(rap)
df1 %>% 
   rap(match = ~ license_index[[as.character(Licensure)]] == Program) %>%
   unnest
#              Program                                        Licensure match
#1 Elementary Education Content Area - Elementary Education (Grades 1-6)  TRUE
#2 Elementary Education      Content Area - Secondary Math (Grades 7-12) FALSE
#3       Secondary Math      Content Area - Secondary Math (Grades 7-12)  TRUE
#4       Secondary Math                   Mathematics (Grades 7-12) 1706  TRUE
#5        Secondary ELA       Content Area - Secondary ELA (Grades 7-12)  TRUE
#6        Secondary ELA    Content Area - Early Childhood (preK-Grade 3) FALSE

文档