关于表单标签内的脚本标签

时间:2013-03-12 06:19:12

标签: javascript html

我在select标签的侧面添加了一个脚本标签,可以动态创建选项。该函数工作正常,但W3C验证器给出了4个有关此语法的错误。如果你们能找到解决这个问题的方法,那将会很有帮助。

这是重复2次的 2错误

1。文档类型不允许使用元素“script”

2。 year_option(); “完成”的结束标记未完成

3 个答案:

答案 0 :(得分:2)

1)<select>可以包含的唯一标记是<option><optgroup>标记 验证器正在抱怨,因为<script>不是其中之一 - 浏览器正在尽力采用无效标记并将其转换为有效标记,因此尽管它有效,但这就是为什么你会收到错误,如果你实际上将<script>标签放在<select>

2)您的脚本标记应位于页面的底部,而不是使用document.write将选项标记放在那里,使用DOM方法在事实之后向select元素添加选项

<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);

有更快,更整洁,或更精细或更灵活的方式,但这比“正确的方式”更接近:

<select>
    <script>document.write("<option value=\"" + i + "\">one</option>");</script>
</select>

或者你现在拥有的任何东西。 如果没有为此目的使用/编写模板库,JS就不应该像这样模板化。

答案 1 :(得分:0)

1)脚本标签应位于头部,或者可能位于文档的其他位置,但不能位于选择标签内

2)看起来你错过了一个标签,或者因为第一次错误而找不到标签。

答案 2 :(得分:0)

您可以将JavaScript放在select标记之外,以后可以在页面加载后在页面上呈现option标记时附加select标记使用$(document).ready

您可以通过将JavaScript放在单独的文件中来标准化您的代码,您可以这样做

$(document).ready(function(){
//Your code to init all things,
//e.g. load options in select box etc..
//so It will be easy later to maintain the code, all init code will go here
});

或者,如果您不使用jquery,则可以使用以下代码

function your_function(){
//your init code will go here
}
document.getElementsByTagName("body")[0].onLoad = your_function;

就是这样,将代码放在your_function()