我已经查看了网络/其他问题以寻求帮助,但无法完全弄清楚并假设我没有使用正确的关键字。
我正在尝试根据用户从网络表单的下拉菜单中选择的值来做某事。逻辑是;
- 用户从下拉列表中选择一个选项
- 该脚本检查该选项是否在数组 1,2,3,4 中
- 根据它所在的数组,它显示不同的 HTML div
这在我的脑海中听起来很简单,但我不知道从哪里开始。一如既往地感谢任何帮助。
这样做真的很快,所以我相信它可以改进。
我想到了两种方法,第一种是使用.indexOf
:
<script type="text/javascript>
$(document).ready(function()
{
var selectedVal = 'asd';
var selectedIndex;
var arrayHolder; //should hold the array the value was found in
var arr1 = ['huh', 'asd'];
var arr2 = ['asdasd'];
var arr3 = ['asdasdasd'];
var arr4 = ['asdasdasdasd'];
//arr1
arrayHolder = arr1;
selectedIndex = arrayHolder.indexOf('asd');
if (!selectedIndex)
{
//arr2
arrayHolder = arr2;
selectedIndex = arrayHolder.indexOf('asd');
if (!selectedIndex)
{
//arr3
arrayHolder = arr3;
selectedIndex = arrayHolder.indexOf('asd');
if (!selectedIndex)
{
//arr4
arrayHolder = arr4;
selectedIndex = arrayHolder.indexOf('asd');
if (!selectedIndex)
{
alert(selectedVal + ' not found in all 4 arrays.');
}
}
}
}
//By here, you should know if a value was found and in which array
alert(arrayHolder);//contains the array in which the value was found
alert(selectedIndex);//The index number where it was found
//test
console.log(arrayHolder[selectedIndex]);
});
</script>
第二种方法是使用 jQuery 的inArray
:
<script type="text/javascript>
$(document).ready(function()
{
var selectedVal = 'asd';
var selectedIndex;
var arrayHolder; //should hold the array the value was found in
var arr1 = ['huh', 'asd'];
var arr2 = ['asdasd'];
var arr3 = ['asdasdasd'];
var arr4 = ['asdasdasdasd'];
//check first array
arrayHolder = arr1;
selectedIndex = $.inArray(selectedVal, arrayHolder);
//check if found in first array, if not check next array
if (!selectedIndex)
{
arrayHolder = arr2;
selectedIndex = $.inArray(selectedVal, arrayHolder);
//check if found in second array, if not check next array
if (!selectedIndex)
{
arrayHolder = arr3;
selectedIndex = $.inArray(selectedVal, arrayHolder);
//check if found in third array, if not check next array
if (!selectedIndex)
{
arrayHolder = arr4;
selectedIndex = $.inArray(selectedVal, arrayHolder);
//check if found in third array, if not check next array
if (!selectedIndex)
{
alert(selectedVal + ' not found in all 4 arrays.');
}
}
}
}
//By here, you should know if a value was found and in which array
alert(arrayHolder);//contains the array in which the value was found
alert(selectedIndex);//The index number where it was found
//test
console.log(arrayHolder[selectedIndex]);
});
</script>
注意: 并非所有浏览器都支持 .indexOf()(特别是 IE)。所以如果你想使用 indexOf(),你应该首先使用下面的代码,在所有浏览器中添加对它的支持(代码归功于 mozilla)。
<script type="text/javascript">
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
</script>