简单的onclick't提交

simple onclick doesn't submit

本文关键字:提交 onclick 简单      更新时间:2023-09-26

我在这个博客上发现了这些很棒的代码片段,可以将语言选择器更改为更时尚的东西。(考虑Twitter引导程序)

它看起来很整洁,但当我真正点击选择时,在onclick上没有提交任何内容。我还不是jquery方面的专家,但在最新的1.8.0版本中,可能有什么东西会阻止onclick工作吗?

<form name="setLang{{ lang.1}}" action="/i18n/setlang/" method="POST">{% csrf_token %}
   <input name="next" type="hidden" value="{{ redirect_to }}" />
   <input type="hidden" name="language" value="{{ lang.0 }}" />
   <a href="#" onclick="document.setLang{{ lang.1 }}.submit(); return false;">{{ lang.1 }}</a>
</form>

您不能使用document.setLang{{ lang.1 }}来获取form。这不是DOM元素的有效名称。JavaScript将在遇到的第一个空白处中断处理,并抛出错误。

我强烈建议您使用有效的name值,但如果您确实需要继续使用该值,则可以使用document.getElementsByName("setLang{{ lang.1}}")[0].submit()访问元素。​​​​

表单名称中有空格这一事实意味着你无法按预期方式访问DOM中的表单项。我会给表单一个不包含空格的id,并以这种方式访问它。

<form name="setLang{{ lang.1}}" id="setLang" action="/i18n/setlang/" method="POST">{% csrf_token %}
   <input name="next" type="hidden" value="{{ redirect_to }}" />
   <input type="hidden" name="language" value="{{ lang.0 }}" />
   <a href="#" onclick="document.setLang.submit(); return false;">{{ lang.1 }}</a>
</form>

另外,请参阅此处:使用输入名称中的javascript空格访问HTML输入字段