关于表单标签中的脚本标签 [英] about script tags inside form tags
问题描述
我在动态创建选项的选择标签旁边添加了一个脚本标签.该函数工作正常,但 W3C 验证器给了我 4 个关于此语法的错误.如果你们能帮我找到解决这个问题的办法.
i have added a script tag in side a select tag which creates options dynamically. The function works fine but the W3C validator gives me 4 errors regarding this syntax. It will be helpful if you guys could find me a solution for this problem.
这些是重复 2 次的 2 个错误.
These are the 2 errors that repeat 2 times.
1. 此处的文档类型不允许元素脚本"
1. document type does not allow element "script" here
2. year_option();未完成的选择"的结束标记
2. year_option(); end tag for "select" which is not finished
推荐答案
1) 可以拥有的标签只有
和 <代码>
1) the only tags that <select>
can have are <option>
and <optgroup>
tags
the validator is complaining because <script>
is not one of those things -- the browser is doing its best to take your invalid markup and turn it into something valid, so despite the fact that it works, that's why you get the error, if you're actually putting <script>
tags inside of a <select>
2) 你的脚本标签应该在你的页面底部,而不是使用 document.write
把选项标签放在那里,使用 DOM 方法在事后向 select 元素添加选项
2) your script tags should be at the bottom of your page, and instead of using document.write
to put option tags there, use DOM methods to add options to the select element after the fact
<select name="select-box"></select>
<!-- ...rest of page... -->
<script src="external-script.js"></script>
/* contents of external-script.js */
var select_box = document.querySelector("select[name=select-box]"),
bob_opt = document.createElement("option"),
doug_opt = document.createElement("option");
bob_opt.value = "Bob";
doug_opt.value = "Doug";
bob_opt.appendChild(document.createTextNode("Bob"));
doug_opt.appendChild(document.createTextNode("Doug"));
select_box.appendChild(bob_opt);
select_box.appendChild(doug_opt);
有更快、更整洁、更精细或更灵活的方法来做到这一点,但这比以下方法更接近正确的方法":
There are faster and neater, or more-elaborate or more flexible ways of doing this, but this is closer to the "right way" than something like:
<select>
<script>document.write("<option value=\"" + i + "\">one</option>");</script>
</select>
或者任何你目前可能拥有的东西.JS 并不意味着要像那样模板化,不为此目的使用/编写模板库.
Or whatever you might currently have there. JS is not meant to be templated like that, without using/writing a templating library for that purpose.
这篇关于关于表单标签中的脚本标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!