Javascript和HTML





$( document ).ready(function() {
    var inputMessage = $("#inputMessage");
    var sendButton = $("#sendButton");
    console.log(inputMessage.value); //->undefined
    inputMessage.value = "hello";
    console.log(inputMessage.value); //->"hello"

<!DOCTYPE html>
<html lang="es">
<head>
	<title>Chat de Hernan</title>
	<!--jquery-->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
	<script type="text/javascript" src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
	<!--bootstrap-->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
</head>
<body>
	<div class="input-group">
		<input id="inputMessage" class="form-control" type="text" value="goodbye" placeholder="Escriba aqui">
		<span class="input-group-btn">
			<button id="sendButton" class="btn btn-default">Enviar</button>
		</span>
	</div>
	<!--js-->
	<script type="text/javascript" src="script.js"></script>
</body>
</html>





我遇到的问题是值undefined和“ hello”与值再见不同。

<input id="inputMessage" class="form-control" type="text" value="goodbye" placeholder="Escriba aqui">


这怎么可能? value =“ goodbye”语句指出输入具有“ goodbye”值,但是javascript表示该值是未定义的,请记住是“ hello”。

最佳答案

定义var inputMessage = $("#inputMessage");将使inputMessage jQuery元素具有方法val()来获取/设置元素值。

因此,使用inputMessage.val()inputMessage.val('hello')代替'inputMessage.value'来设置新值。

10-07 17:26