>我在页面上有几个非常简单的表单,所有表单的结构如下。我只需要在按下链接时提交带有值的表单。有没有办法在单击的表单中提交值,而无需唯一标识每个表单?
<form action="result.php" method="post">
<input name="id" type="hidden" value="10" />
<a href="#" onclick="document.getElementByName('id').submit();">
some text with styling to click
</a>
</form>
尝试在this.parentElement
上调用.submit()
<form action="result.php" method="post">
<input name="id" type="hidden" value="10" />
<a href="#" onclick="this.parentElement.submit();">
some text with styling to click
</a>
</form>
只需使用一个按钮提交表单,并按照您喜欢的方式设置样式。
默认情况下,按钮提交表单。
button {
background:none!important;
border:none;
padding: 0;
margin : 0;
cursor: pointer;
}
button:hover {
color: green;
text-decoration: underline;
}
<form action="result.php" method="post">
<input name="id" type="hidden" value="10" />
<button>Button that submits the form</button>
</form>
如果您使用的是jquery
$('form [name=myForm]').on('submit' function(e){
e.preventDefault();
});
你可以不用jquery,只需给表单一个ID复制下面的代码。
<form action="result.php" method="post" id='myForm'>
<input name="id" type="hidden" value="10" />
<a href="#" onclick='document.getElementById("myForm").submit();'>
some text with styling to click
</a>
</form>
我认为使用jQuery应该可以工作:
$('form a').click(function(e){
var form = $(this).parent('form');
form.submit();
return false;
});
这样,您可以在表单中找到链接,并为每个链接添加一个单击事件。如果单击链接,则仅提交周围的表单。这是适用于所有表单的解决方案。因此,您无需ugly
单击每个破坏代码的链接。
没有jQuery使用:this.parentElement.submit();
this
是您的链接元素,parentElement
是您要提交的表单。