如何以HTML形式指定按钮的行为?

时间:2018-07-16 14:46:14

标签: javascript html

我的页面被编码为这样,我所拥有的一切都以表格的形式出现。

<form onsubmit='return validate()' action='#' method='post'>
    <button class='accordian'>Drop Stuff1</button>
        <div class='panel'>
            //stuff here
        </div>
        <div>
            //stuff here too
        </div>
    <button class='accordian'>Drop Stuff2</button>
        <div class='panel'>
            //and here
        </div>
        <div>
            //and here too
        </div>
    <input type='submit' value='Submit!'>
</form>

问题在于,当我单击Accordian的任何按钮时,它会运行我的validate()函数。我该如何设置它,以便仅当用户按下我的onsubmit='return validate()按钮时才调用表单的<input type='submit' value='Submit!'部分?

我尝试摆脱<form onsubmit='return validate()'并将其放置到提交按钮(即<input type='submit' onsubmit='return validate()')上,也尝试使用onclick进行替换。每次按下手风琴面板时,我的页面都会保持刷新状态,因为似乎每次单击都提交表单。我该如何规避这种行为,并确保只有“提交”按钮指示是否要提交表单?

5 个答案:

答案 0 :(得分:3)

default type of a button element is submit。将其更改为button,它将不会提交表单并调用您的函数。

例如<button type="button" class='accordian'>Drop Stuff2</button>

答案 1 :(得分:0)

type="button"添加到按钮

答案 2 :(得分:0)

单击onsubmit-event类型的元素时,将触发submit。因此,只需将type="button"添加到其他按钮,因为默认值为submit

答案 3 :(得分:0)

当然,另一个选择是将对validate函数的调用从<form>标记移到<intput>标记

<form  action='#' method='post'>
    <button class='accordian'>Drop Stuff1</button>
        <div class='panel'>
            //stuff here
        </div>
        <div>
            //stuff here too
        </div>
    <button class='accordian'>Drop Stuff2</button>
        <div class='panel'>
            //and here
        </div>
        <div>
            //and here too
        </div>
    <input type='submit' value='Submit!' onclick='return validate();'>
</form>

答案 4 :(得分:0)

为什么要使用“风琴”按钮?诸如div / span / li之类的其他东西看起来更易于样式设计和更合理。

相关问题