如何在方法外部访问jquery更改事件值?

问题描述 投票:0回答:2

我有一个输入文本字段:

<input type="text" id="from_input" class="form-control" placeholder="FROM">

我想获得文本值的变化。这是我的jquery代码:

<script>
  var fromValue;
  $(document).ready(function(){
    $("#from_input").change(function() {
      fromValue = $(this).val();
    });
    console.log(fromValue);
  });
</script>

我将fromValue变量定义为未定义。我需要获取文本字段值,以便在整个脚本中进行进一步的计算。我该如何实现?

jquery jquery-events
2个回答
0
投票

您可以使用事件参数。该事件包含目标元素。

<script>
  var fromValue;
  $(document).ready(function(){
    $("#from_input").change(function(event) {
      fromValue = event.target.value;
    });
    console.log(fromValue);
  });
</script>

0
投票

示例:

$(function() {
  $('#itext').keyup(function() {
    var text = $(this).val();
    $('#result').text('Your text: ' + text);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="itext">
<br><label id="result">Your text: </label>
© www.soinside.com 2019 - 2024. All rights reserved.