我正试图通过200+条目的选择列表,并单击每一个。当单击一个元素时,它会执行一个函数selectCountry(),该函数会向表中添加一行。我想让它创建一个表与每个选项选定。感兴趣的页面是:http://www.world-statistics.org/result.php?code=ST.INT.ARVL?name=International%20tourism,%20number%20of%20arrivals。
到目前为止,我有以下内容,但它似乎不起作用:
var sel = document.getElementById('selcountry');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {selectCountry(opt.value)}
我正在尝试在Chrome的控制台中这样做。
开发工具最有用的特性之一是,当您编写函数的名称时,您将返回它的源代码。以下是selectCountry
函数的源代码:
function selectCountry(select) {
if (select.value == "000") return;
var option = select.options[select.selectedIndex];
var ul = select.parentNode.getElementsByTagName('ul')[0];
var choices = ul.getElementsByTagName('input');
for (var i = 0; i < choices.length; i++)
if (choices[i].value == option.value) {
$("#selcountry:selected").removeAttr("selected");
$('#selcountry').val('[]');
return;
}
var li = document.createElement('li');
var input = document.createElement('input');
var text = document.createTextNode(option.firstChild.data);
input.type = 'hidden';
input.name = 'countries[]';
input.value = option.value;
li.appendChild(input);
li.appendChild(text);
li.onclick = delCountry;
ul.appendChild(li);
addCountry(option.firstChild.data, option.value);
$("#selcountry:selected").removeAttr("selected");
$('#selcountry').val('');
}
你的缺陷现在很明显。selectCountry
接受整个select元素作为参数,而不是 select的值(这是一个糟糕的设计,但meh)。与其传递元素的值,不如改变它的索引:
var sel = document.getElementById('selcountry');
var opts = sel.options;
for(var i = 0; i < opts.length; i++) {
sel.selectedIndex = i
selectCountry(sel)
}