为什么jquery无法访问html输入

时间:2018-08-04 04:03:16

标签: jquery html

我很震惊,这里发生了什么,只是这里缺少的简单的东西。为什么HTML输入变量无法在jquery中访问,我尝试使用ID选择器,名称属性。真的很奇怪。

$(document).ready(function(){
  var heading = $('#heading').val();
  var heading1 = $('#heading').text();
  var heading2 = $('input[name=heading]').val();
			$('#submit').click(function(){
      alert(heading);
      alert(heading1);
      alert(heading2);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<form action="">
<table>
<tr>
<th>
Heading
</th>
<td>
<input type="text" name="heading" id="heading">
<input type="submit" id="submit" name="submit">
</td>
</tr>
</table>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:4)

您需要在click事件中获取值,text()也将无法获取输入值

$(document).ready(function() {
  $('#submit').click(function() {
    var heading = $('#heading').val();
    var heading1 = $('#heading').text(); //this will not get the value
    var heading2 = $('input[name=heading]').val(); // this will be the same as the heading var
    alert(heading);
    alert(heading1);
    alert(heading2);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="">
  <table>
    <tr>
      <th>
        Heading
      </th>
      <td>
        <input type="text" name="heading" id="heading">
        <input type="submit" id="submit" name="submit">
      </td>
    </tr>
  </table>
</form>