在 HTML5 中,我有一个下拉菜单。当选择不同的选项时,我隐藏或显示页面的不同部分。这是该脚本:
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
但是我现在想做的是,在另一个脚本中从下拉列表中预加载一个选项。我可以用这个脚本轻松做到这一点:
setSelectedIndex(document.getElementById('target'),'content_1');
function setSelectedIndex(s, valsearch)
{
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++)
{
if (s.options[i].value == valsearch)
{
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
return;
}
这就是我的问题出现的地方,我的下拉菜单将获得我想要的值,但是在选择该选项时我想要显示的部分不会出现。
最佳答案
这是因为更改事件需要从浏览器发生。
When the user commits the change explicitly (e.g. by selecting a value from a 's dropdown with a mouse click, by selecting a date from a date picker for , by selecting a file in the file picker for , etc.);
如果您使用 Jquery,您可以:
$("#id").val("value").trigger('change');
或者如果您不担心构建事件对象,您可以使用 javascript:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");
关于javascript - 从另一个脚本调用脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31455769/