gpt4 book ai didi

javascript - 在html提交按钮中调用javascript函数

转载 作者:行者123 更新时间:2023-11-30 07:08:25 25 4
gpt4 key购买 nike

我有一个表单,我想根据用户的决定隐藏或显示它。我在外部 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 using value 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com