jQuery的.获取按钮单击事件时文本输入字段的值? [英] jQuery. Get text input field's value on button clicking event?

查看:72
本文介绍了jQuery的.获取按钮单击事件时文本输入字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

html:

<div id="search">
  <input id="term" type="text" value="enter your search" />
  <button id="hit" type="button" name="">Search</button>
</div>

jQuery:

$(document).ready(function() {
  var term = $('#term').val();
  $('#hit').click(function() {
    alert(term);
  });
});

问题在于,无论我在输入字段中键入什么内容,然后单击按钮,它始终会警告原始输入值输入搜索".

The problem is that , no matter what I type in the input field, then hit the button, it always alert the original input value which is "enter your search".

我该如何解决?

推荐答案

您遇到的问题是,整个代码块都在DOM ready事件上执行.

The problem you're having is that this whole block of code gets executed on the DOM ready event.

var term = $('#term').val();仅被评估一次,并将输入搜索内容"存储在术语变量中.这就是为什么无论您将值更改为什么,该变量在呈现页面时仍保持初始值.

var term = $('#term').val(); is being evaluated only once and storing 'enter your search' in the term variable. This is why no matter what you change the value to, the variable still holds the initial value when the page was rendered.

相反,您应该执行的操作类似于以下内容:

Instead what you should do is something more like the following:

jQuery

$(document).ready(function() {
  $('#hit').click(function() {
    alert($('#term').val());
  });
});

在这段代码中,单击事件侦听器触发时,将对具有id项的元素的值进行评估.

In this bit of code, the value of the element with id term is evaluated when the click event listener fires.

这篇关于jQuery的.获取按钮单击事件时文本输入字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆