5

可能重复:
根据值列表检查变量是否相等
Javascript if 语句具有多个允许条件

我必须在下拉列表 (ul) 中单击 253 个项目 (li) 中的相同 21 个。

滚动我必须为 500 多页上的同一个列表执行此操作,我想我可以 Javascript 注入每个 ul,循环并单击恰好是 21 个之一的每个 li。看来我不能做类似的事情

 if(item[i] === ('aasdf'|'basdf'|'cwefw'|'asdfd'|'trehe'|'ferth'|'erthg'|'erthh'|'ierth'|'jeth'|'kerth'|'lerth'|'merth'|'psdfg'|'gregq'|'rsrgs'|'sress'|'srget'|'sergu'|'sdfgsv'))

有没有一种语法更简洁的方式来编写下面这个丑陋的 if 语句?

var item = document.getElementById('myDropdownList').getElementsByTagName('li');

for (i=0;i<item.length;i++){

    if(item[i].innerText === 'Argentina' | item[i].innerText === 'Australia' | item[i].innerText === 'Brazil' | item[i].innerText === 'Canada' | item[i].innerText === 'China' | item[i].innerText === 'Colombia' | item[i].innerText === 'France' | item[i].innerText === 'Germany' | item[i].innerText === 'Indonesia' | item[i].innerText === 'India' | item[i].innerText === 'Italy' | item[i].innerText === 'Japan' | item[i].innerText === 'Malaysia' | item[i].innerText === 'Mexico' | item[i].innerText === 'Philippines' | item[i].innerText === 'Russia' | item[i].innerText === 'South Africa' | item[i].innerText === 'Sweden' | item[i].innerText === 'Switzerland' | item[i].innerText === 'United Kingdom' | item[i].innerText === 'USA'){

    item[i].click();

    }

}
4

2 回答 2

6

您可以使用变量和多重比较,但这仍然很长:

var text = item[i].innerText;
if (text === 'Argentina' | text === 'Australia' | text === 'Brazil' | text === 'Canada' | text === 'China' | text === 'Colombia' | text === 'France' | text === 'Germany' | text === 'Indonesia' | text === 'India' | text === 'Italy' | text === 'Japan' | text === 'Malaysia' | text === 'Mexico' | text === 'Philippines' | text === 'Russia' | text === 'South Africa' | text === 'Sweden' | text === 'Switzerland' | text === 'United Kingdom' | text === 'USA')

或者您可以只使用一个数组并检查字符串是否包含在其中。

var matches = ['Argentina','Australia','Brazil','Canada','China','Colombia','France','Germany','Indonesia','India','Italy','Japan','Malaysia','Mexico','Philippines','Russia','South Africa','Sweden','Switzerland','United Kingdom','USA'];
if (~ matches.indexOf(item[i].innerText) …

然而,对于复杂的!= -1比较和旧 IE 中缺乏原生indexOf的情况,人们倾向于使用正则表达式:

var regex = /Argentina|Australia|Brazil|Canada|China|Colombia|France|Germany|Indonesia|India|Italy|Japan|Malaysia|Mexico|Philippines|Russia|South Africa|Sweden|Switzerland|United Kingdom|USA/
if (regex.test(item[i].innerText)) …
于 2012-12-19T18:58:28.863 回答
4
var options = ['Argentina', 'Australia', 'Brazil', 'Canada', ...];
if (options.indexOf(item[i].innerText) !== -1){
  // item[i] was found in options
}

类似的东西?使用Array.indexOf(除非我读错了问题?在这种情况下发表评论,我会尽我所能重新工作我的答案)

于 2012-12-19T18:51:30.667 回答