我是一名网络开发学生,我需要一些帮助。我有下面的代码;如何仅在提交表单时才使其工作,而不是单击文本字段。我也希望它能在.thanks Div中获取并插入textField的值。请帮我学习。
<script type="text/javascript">
$(document).ready(function(){
$(".quote").click(function(){
$(this).fadeOut(5000);
$(".thanks").fadeIn(6000);
var name = $("#name").val();
$("input").val(text);
});
});
</script>
<style type="text/css">
<!--
.thanks {
display: none;
}
-->
</style>
</head>
<body>
<form action="" method="get" id="quote" class="quote">
<p>
<label>
<input type="text" name="name" id="name" />
</label>
</p>
<p>
<label>
<input type="submit" name="button" id="button" value="Submit" />
</label>
</p>
</form>
<div class="thanks"> $("#name").val(); Thanks for contacting us, we'll get back to you as soon as posible</div><!-- End thanks -->
答案 0 :(得分:0)
这里有几个问题:
通过使用$('.quote').click()
,您将在<form>
中包含的任何元素上的任何点击事件上设置处理程序。如果您只想捕获提交事件,则应在提交按钮上设置单击处理程序:
// BTW, don't use an id like "button" - it'll cause confusion sooner or later
$('#button').click(function() {
// do stuff
return false; // this will keep the form from actually submitting to the server,
// which would cause a page reload and kill the rest of your JS
});
或者,最好是表单上的提交处理程序:
// reference by id - it's faster and won't accidentally find multiple elements
$('#quote').submit(function() {
// do stuff
return false; // as above
});
提交处理程序更好,因为它们可以通过其他方式提交表单,例如在文本输入中点击Enter
。
此外,在您隐藏的<div>
中,您使用纯文本而不是<script>
标记放入Javascript,这样就可以在屏幕上看到。您可能需要一个可以引用的占位符元素:
<div class="thanks">Thanks for contacting us <span id="nameholder"></span>, we'll get back to you as soon as possible</div>
然后您可以将名称粘贴到占位符中:
var name = $("#name").val();
$('#nameholder').html(name);
我不知道您要对该行$("input").val(text);
做什么 - 这里没有定义text
,所以这没有任何意义。
答案 1 :(得分:0)
这有点粗糙,准备好但是应该让你去
$(document).ready(function(){
$("#submitbutton").click(function(){
//fade out the form - provide callback function so fadein occurs once fadeout has finished
$("#theForm").fadeOut(500, function () {
//set the text of the thanks div
$("#thanks").text("Thanks for contacting us " + $("#name").val());
//fade in the new div
$("#thanks").fadeIn(600);
});
});
});
我改变了一下html:
<div id="theForm">
<form action="" method="get" id="quote" class="quote">
<p>
<label>
<input type="text" name="name" id="name" />
</label>
</p>
<p>
<label>
<input type="button" name="submitbutton" id="submitbutton" value="Submit" />
</label>
</p>
</form>
</div>
<div id="thanks">Thanks for contacting us, we'll get back to you as soon as posible</div><!-- End thanks -->