如何最好地建立链接提交表单 [英] How best to make a link submit a form
问题描述
获取常规锚点(< a href =...>
)以提交单击时嵌入的表单的最佳方式是什么?
< form>
< ul>
< li>
< p>
该链接可以在任何级别上< span>嵌入< a href =onclick =?>< / a>< / span>
的形式,所以this.parentNode.parentNode ...是不好的。 :(
< / p>
< / li>
< / ul>
< / form>
我知道使用jQuery最简单的方法是
$('#myLink')。click(function(){
$(this).parents('form:first')。submit();
});
...但我试图找到一种不使用库的方法。
编辑:我真的想找到一种不需要表单知识的方法(例如:名称,ID等),这与您如何将它放在输入元素上类似:< input onclick =this.form.submit()/> $ c $
循环通过父节点,直到找到具有标记名的元素,表明它是表单!
$ p $
< form>
< ul>
< li>
< p>
链接可以是&l t; span>嵌入式< a href =onclick =get_form(this).submit(); (
< / p>< / span>
) ;
< / 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:在祖先中找不到表单
//]]>
< / script>
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>
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.
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屋!