【发布时间】:2016-09-26 15:22:50
【问题描述】:
无休止地在谷歌上搜索,转圈圈。
我有一个页面,上面有三个表单。 一个表单提供了项目的高级搜索,我根据选择的内容在表单的选择框上运行了 javascript。选择输入是分层的,如果顶层发生变化,下面的选择框会被清除,然后由 ajax 用一组新的选项填充。我无法让 clearoptions 功能正常工作。
所以,表格看起来像这样(我已经简化了):
<html>
<body>
<form id="searchform">
<select id="toplevel" onChange="searchform(this.value,'toplevel',this.form)">
<option value="option1">Top 1</option>
<option value="option2">Top 2</option>
<option value="option3">Top 3</option>
</select>
<select id="mediumlevel" onChange="searchform(this.value,'mediumlevel',this.form)">
<option value="option1">Medium 1</option>
<option value="option2">Medium 2</option>
<option value="option3">Medium 3</option>
</select>
<select id="lowlevel">
<option value="option1">Low 1</option>
<option value="option2">Low 2</option>
<option value="option3">Low 3</option>
</select>
</form>
</body>
</html>
当某些事情发生变化时我调用的 Javascript 函数如下所示。
function searchform(value, changed, theform)
{
if(changed == "toplevel")
{
//clear both mediumlevel and lowlevel boxes if toplevel is changed
clearoptions(["mediumlevel","lowlevel"],theform);
return;
}
else if (changed == "mediumlevel")
{
// clear just lowlevel box if mediumlevel is changed
clearoptions(["lowlevel"],theform);
return;
}
}
这是 clearoptions 函数,用于删除 DOM 中的当前选项。我从 searchform 函数传入一组 id,然后循环遍历它们以清除多个选择框。之后的下一个函数通过 ajax 引入了新选项,但这里不需要。我需要先完成这项工作。
function clearoptions(ids,thisform)
{
for (i=0; i<ids.length; i++)
{
// this is the line where it gives me the error:
// TypeError: thisform.getElementById is not a function
var tempid = thisform.getElementById(ids[i]);
tempid.length = 0;
var createoption=tempid.createElement('option');
createoption.text='Include All';
createoption.value='All';
tempid.add(createoption,null)
}
}
我只是不断收到 tempid 不是函数错误。
我不想硬编码函数中的表单 ID 的原因是,我在网站的不同页面上有许多相似的搜索表单,我想创建这些函数,我可以从中调用如果可能的话。 救命!
【问题讨论】:
-
这不是一个函数。
getElementById是document唯一的方法。 -
你可能想要
theform.querySelector。 -
谷歌搜索表明这是针对 CSS 的?
-
@TVRV8S 我只是想知道,你用谷歌搜索了什么。可能你还没有找到MDN: querySelector
标签: javascript arrays forms function getelementbyid