如何不在 jQuery 中提交表单

How to not to submit form in jQuery

我对我在我的网站上尝试的这段代码有疑问。我想尽量减少文字的大小,所以我尝试通过简单的点击来隐藏对象。但这确实总是提交我的表格。

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#hide").click(function(){
        $("table").hide();
    });
    $("#show").click(function(){
        $("table").show();
    });
});
</script>
</head>
<body>


<table style="border:solid #FFFFFF 2px;
background-color:#0000ff;height:1px;width:300px;
text-align:left;" "empty-cells:hide;" border="1" cellpadding="1" cellspacing="1">
    <tr>
        <th>Test</th>
        <th>Extras</th>
        <th>Extras</th>
    </tr>
</table>
<br>

<button id="hide">Hide</button>
<button id="show">Show</button>

</body>
</html>

[submit class:button id:form-submit "Send"]

您需要为事件使用 .preventDefault() 函数。当您单击按钮时,这会阻止发送。请注意,您需要在参数 (e) 中发送事件。

一个例子:

$("#hide").click(function(e){
    e.preventDefault();
    $("table").hide();
});

这是一个缩短脚本的解决方案

$(document).ready(function(){
    $("#switch").click(function(){
        $("table").toggle();
        $("#switch").text(($("#switch").text() == "Hide") ? "Show" : "Hide");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table style="border:solid #FFFFFF 2px;
background-color:#0000ff;height:1px;width:300px;
text-align:left;" "empty-cells:hide;" border="1" cellpadding="1" cellspacing="1">
    <tr>
        <th>Test</th>
        <th>Extras</th>
        <th>Extras</th>
    </tr>
</table>
<br>

<button id="switch">Hide</button>

在按钮中添加type="button"

<button type="button" id="hide">Hide</button>
<button type="button" id="show">Show</button>

好吧,这里没有元素,现在可以正常显示和隐藏了。但可能是当您以某种形式使用它时,问题就会发生。要解决该问题,请使用以下内容:

$(document).ready(function(event){
    $("#hide").click(function(){
        $("table").hide();
        return false;
    });
    $("#show").click(function(){
        $("table").show();
        return false;
    });
});

--或--

$(document).ready(function(event){
    event.preventDefault();
    $("#hide").click(function(){
        $("table").hide();
    });
    $("#show").click(function(){
        event.preventDefault();
        $("table").show();
    });
});

工作起来更容易,没有任何其他问题

> <button title="Click to show/hide content" type="button"
> onclick="if(document.getElementById('Funktionen')
> .style.display=='none') {document.getElementById('Funktionen')
> .style.display=''}else{document.getElementById('Funktionen')
> .style.display='none'}">+</button> <div id="Funktionen"
> style="display:none;">   HERE COMES IN WHATEVER YOU WANT TO HIDE WITH
> the + Button </div>