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

标签 javascript html

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

相关文章:

javascript - 从 JQUERY/AJAX 到 Morris.JS 的数据

javascript - AngularJS 良好实践 : Hide/show new DOM elements or compile

php - 删除按钮和确认

html - webkit 渐变和不透明度

javascript - 在我开始输入之前,contentEditable div 中的光标太大

javascript - JW Player安装YouTube嵌入链接

javascript - 在页面中添加两次时 Jquery 库出现问题

javascript - 图像 slider 过渡时间

javascript - JQuery onClick 如何才能在 Div 中显示页面的特定链接?

php - 使用 rowspan 将数据从数据库调用到表中