我正在使用 jQuery。我创建了一个变量并将值存储在其中,但是我无法使用.html()
.
代码
var msg = $("#msg");
var msgvl = msg.val();
var btn = $("#btn");
$(document).ready(function(){
$(btn).click(function(){
$("#reply").html(msgvl);
});
});
HTML
<input type="text" id="msg">
<button id="btn">Send!</button>
<p id="reply"></p>
实际上,当文档呈现时,您的文本框没有任何价值。所以你的代码不起作用。
顺便说一句,您可以通过如下所示的更少代码来做同样的事情:-
//compress code to do the same what you did with your code
$(document).ready(function(){
$(btn).click(function(){
$("#reply").html($("#msg").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="msg" value="abc"><!-- initially value required to make your code work-->
<button id="btn">Send!</button>
<p id="reply"></p>
注意:- 如果您最初也添加值,当新值输入到文本框中时,您的代码将不起作用,因为您的代码已经采用了初始值。所以如果你想让它为改变的值工作,那么你必须把上面的所有代码$(document).ready(function(){..});
放在click
函数中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句