JavaScript:如何从keyup事件中获取发件人输入元素的值?

问题描述:

我需要捕获keyup事件以在用户键入输入时提供实时验证(仅当输入失去焦点时才会触发change事件).

I need to capture the keyup event to provide live validation when user is typing in an input (change event fires only when the input loses focus).

我无法获得触发evnt的输入的编辑值.

I am having trouble getting the edited value of the input that fired the evnt.

该代码还在计时器上运行,以防止用户键入时多次调用(仅每500毫秒触发一次).

The code also runs on timer to prevent multiple calls when user is typing (fires only every 500 ms).

我有几个带有"priceinput"类的输入,并分别附加到每个的keyup事件上,如下所示:

I have several inputs with class "priceinput" and attach to keyup event of each like the following:

<script language="javascript" type="text/javascript">
    var timer;
    $(document).ready(function() 
    {
        $(".priceinput").each(function() 
        {
            $(this).keyup(function(e) 
            { 
                clearTimeout(timer);
                timer = setTimeout(function() 
                {     
                //how to get the value of the input element that was changed?  
                var value = ???;
                    $.getJSON('/Validator/IsValidInput', { input: value },
                    function(response) 
                    {
                      //indicate if input is correct
                    });
                }, 500);
            });
        });
     });
</script>

为了获取发送者的输入值,我尝试了$(this).valthis.val()e.target.val(),但似乎都无法正常工作.

To get the sender input value, I have tried $(this).val, this.val(), e.target.val() but none seem to work.

如何获取发件人输入的值?

How do I get the value of the sender input?

问题是,在超时功能中,您丢失了对输入元素的"this"引用.尝试这样的事情:

The problem is that in your timeout function, you've lost the "this" reference to the input element. Try something like this:

$('.priceinput').keyup(function(e) {
  var $input = $(this);
  clearTimeout(timer);
  timer = setTimeout(function() { 
    var value = $input.val();
    $.getJSON( ... );
  }, 500);
});