使用jQuery单击隐藏/显示按钮时页面重新加载 [英] Page reloads on hide/show button click using jQuery
问题描述
我正在使用jQuery通过单击显示/隐藏按钮来显示/隐藏 div
.但是,我的代码无法正常工作,因为它每次都返回到我单击按钮之前的状态.我几乎可以肯定这是由于页面重新加载所致,因为每次单击按钮时,页面都会重新加载.
有人知道这可能是什么原因吗?
I'm using jQuery to show/hide a div
by clicking on the show/hide buttons. However, my code doesn't work because every time it returns to the way it was before when I click on my buttons. I'm almost sure that this is due to a page reload, because every time I click on a button it reloads the page.
Does anybody know what could be the reason behind this?
这是重要的代码块:
<form role="form" method="post" action="./something.php">
...
<button id="hidemultmachines" onclick="$('#multmachines').hide(); $(this).hide(); $('#showmultmachines').show();">
Hide section below ...
</button>
<button id="showmultmachines" onclick="$('#multmachines').show(); $(this).hide(); $('#hidemultmachines').show();">
... Create multiple entries
</button>
<div id="multmachines">
...
</div>
<div>
<div>
<input type="hidden" name="total" value="{ $smarty.section.i.total }">
<button type="submit" name="Submit" value="Save">Save</button>
</div>
</div>
</form>
这是我的jQuery标头中的代码:
And this is my jQuery code in the header:
$(document).ready(function(){
$('#hidemultmachines').hide();
$('#multmachines').hide();
}
当我将按钮放在表格之外时,它可以工作.为什么?
When I put the buttons outside the form it works. Why?
推荐答案
这是因为您的 button
元素未指定 type
,默认情况下未指定 button
元素的 type
设置为提交".当您单击按钮之一时,它们会尝试提交您的表单.只需指定按钮"的类型
即可解决此问题:
That's because your button
elements have no type
specified, and by default button
elements have their type
set to "submit". When you click one of the buttons, they attempt to submit your form. Simply specifying a type
of "button" will fix this:
<button type="button" class="close" id="hidemultmachines" onclick="..."></button>
这篇关于使用jQuery单击隐藏/显示按钮时页面重新加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!