我正在使用Javascript书签来自动填写页面上的表单.给出的一些选项是下拉选项,根据使用onchange()选择的内容显示不同的选项.我有类似这样的代码:
/* Gets first drop down and sets value to first in list */
var dropDown1 = document.getElementById("dropDown1Name");
dropDown1.value = "option1InDropDown";
dropDown1.onchange();
/* Sets value of second drop down to option that is available when first option in first drop down is selected */
var dropDown2 = document.getElementById("dropDown2Name");
dropDown2.value = "optionRevealedByDropDown1Change";
Run Code Online (Sandbox Code Playgroud)
但是这不起作用,因为onchange()在我将其设置为值时不会填充第二个下拉列表.当脚本完成执行时,dropDown2中没有设置值.我已经尝试了几种方法使代码"等待"但我无法找到正确的解决方案.任何建议表示赞赏.
正如评论中已经指出的那样,问题的一部分是change事件的错误触发。问题的另一部分可能是第二个下拉列表的选项可能仅在收到某些异步操作的结果(例如使用 XMLHttpRequest)后才填充。在这种情况下,即使change事件被正确触发,您的代码仍然需要等待下拉列表填充后再设置其值。一种方法可能基于定期检查下拉列表是否填充了值(例如使用setInterval或setTimeout)。更优雅的方法可以使用MutationObserver等待下拉列表填充值。看看这个片段:
var sel1 = document.querySelector('#sel'),
sel2 = document.querySelector('#sel2');
// Onchange code
sel1.addEventListener('change', function() {
sel2.disabled = false;
// emulate async request for dropdown options
setTimeout(function populateSecondSelect() {
['', 'dynamic1', 'dynamic2'].forEach(function(val) {
var opt = document.createElement('option');
opt.setAttribute('value', val);
opt.textContent = val || '-';
sel2.appendChild(opt);
});
}, 2000);
});
// Code to trigger events (based on http://stackoverflow.com/a/2490876/2671392)
function triggerEvent(type, element) {
var event; // The custom event that will be created
if (!!window.Event) {
event = new Event(type);
} else if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent(type, true, true);
} else {
event = document.createEventObject();
event.eventType = type;
}
event.eventName = type;
if (document.createEvent) {
element.dispatchEvent(event);
} else {
element.fireEvent("on" + event.eventType, event);
}
}
document.querySelector('#btn').addEventListener('click', function() {
sel1.value = sel1.value === '1' ? '2' : '1';
// trigger change event
triggerEvent('change', sel1);
// set MutationObserver for second dropdown
var observer = new MutationObserver(function(mutations) {
sel2.value = 'dynamic2';
observer.disconnect();
});
// only observe changes in the list of children
var observerConfig = {
childList: true
};
observer.observe(sel2, observerConfig);
});Run Code Online (Sandbox Code Playgroud)
<div>
<input type="button" id="btn" value="Select values" />
<select id="sel">
<option value="" selected>-</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<select id="sel2" disabled>
</select>
</div>Run Code Online (Sandbox Code Playgroud)
但请注意,这MutationObserver在旧版浏览器中不可用。