如何最好地使链接提交表单 [英] How best to make a link submit a form
问题描述
获得常规锚点 (<a href="...">
) 以提交点击时嵌入的表单的最佳方法是什么?
What's the best way to get a regular anchor (<a href="...">
) to submit the form it is embedded in when clicked?
<form>
<ul>
<li>
<p>
The link could be <span>embedded <a href="" onclick="?">at any level</a></span>
in the form, so "this.parentNode.parentNode..." is no good. :(
</p>
</li>
</ul>
</form>
我知道使用 jQuery 最简单的方法是
I know that the easiest way using jQuery would be
$('#myLink').click(function() {
$(this).parents('form:first').submit();
});
...但我试图找到一种不使用库的方法来做到这一点.
...but I'm trying to find a way to do this without using a library.
编辑:我真的想找到一种不需要了解表单的方法(例如:其名称、ID 等).这类似于将它放在输入元素上的方式:<input onclick="this.form.submit()"/>
Edit: I'm really trying to find a method which doesn't require knowledge of the form (eg: its name, id, etc). This would be similar to how you could put this on an input element: <input onclick="this.form.submit()" />
推荐答案
遍历父节点,直到找到一个带有标记名的元素,表明它是一个表单!
loop through parent nodes until you find an element with tagname that indicates it's a form!
<form>
<ul>
<li>
<p>
The link could be <span>embedded <a href="" onclick="get_form(this).submit(); return false">at any level</a></span>
in the form, so "this.parentNode.parentNode..." is no good. :(
</p>
</li>
</ul>
</form>
<script type="text/javascript">
//<![CDATA[
function get_form( element )
{
while( element )
{
element = element.parentNode
if( element.tagName.toLowerCase() == "form" )
{
//alert( element ) //debug/test
return element
}
}
return 0; //error: no form found in ancestors
}
//]]>
</script>
这篇关于如何最好地使链接提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!