我有一个表单,我想根据用户的决定隐藏或显示它。我在外部 javascript 文件中获得了以下函数:
function hide_element() {
$("form").hide();
};
function show_element() {
$("form").show();
};
这就是我调用这些函数的方式:
<button type="submit" onclick="show_element;">show</button>
<button type="submit" onclick="hide_element;">hide</button>
<form>
...
</form>
不幸的是,这不起作用。您知道为什么会这样吗?
最佳答案
因为我们使用 jQuery
我想提出这种方法:
HTML:
<button id='toggleMyForm'>hide</button>
<form id='myForm'>First name:
<br>
<input type=" text " name="firstname " />
<br>Last name:
<br>
<input type="text " name="lastname " />
<br>
<input type="submit" value="Submit"/>
</form>
jQuery:
var myForm = $('#myForm');
var toggleMyForm = $('#toggleMyForm');
toggleMyForm.on('click', function(){
myForm.toggle();
myForm.is(":visible") ? $(this).html('hide') : $(this).html('show');
});
Test here: http://jsfiddle.net/urahara/obm39uus/
NOTE: don't put yourself in the position where you have multiple
submit
buttons in a<form>
, you can distinguish between them by usingvalue
attribute, but still in my opinion it's better to keep clean design with one submit per form.don't repeat
jQuery
fetching calls. make a handle of a element:var myForm = $('myForm');
then use it like this e.g:myForm.show()
关于javascript - 在html提交按钮中调用javascript函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29228163/