Material IO中调用setSelectedIndex提示“不是函数”的问题问询
Got it, let's work through why you're hitting that setSelectedIndex is not a function error with MDC Select. Here are the most common fixes:
Possible Causes & Solutions
1. You might be using an older MDC Web version
MDC Web's API has evolved over versions, and setSelectedIndex as a direct instance method is a relatively recent addition. If you're on an older release, this method lives in the component's foundation layer instead:
// For older MDC versions, use the foundation to call the method filterField.foundation_.setSelectedIndex(1);
Alternatively, a simpler approach that works across most versions is to directly set the selectedIndex property:
filterField.selectedIndex = 1;
2. Verify you're getting a valid MDCSelect instance
Sometimes the issue isn't the method itself—it's that your filterField variable isn't actually a proper MDCSelect instance. Add a quick log to check:
let filterField = mdc.select.MDCSelect.attachTo(document.querySelector(".mdc-select--location")); console.log(filterField); // Check if this shows an MDCSelect object with the method
If it doesn't, double-check:
- Your target element has the required base MDC Select class (
mdc-select) alongside your custom.mdc-select--locationclass - The element follows MDC Select's required DOM structure (it needs child elements like
.mdc-select__anchorand.mdc-select__menu) - Your code runs after the DOM is fully loaded (wrap it in a
DOMContentLoadedlistener or place it at the bottom of your HTML)
3. Ensure correct timing for initialization (for newer MDC versions)
If you're on a recent MDC Web version (v8+), setSelectedIndex should work as a direct instance method—so the problem might be that you're calling it before the component is fully initialized. Wrap your code in a DOM ready listener to fix this:
document.addEventListener('DOMContentLoaded', () => { let filterField = mdc.select.MDCSelect.attachTo(document.querySelector(".mdc-select--location")); filterField.setSelectedIndex(1); // This should work now });
If your select menu is dynamically added to the DOM (e.g., via AJAX), make sure you call attachTo after the element is inserted into the page.
内容的提问来源于stack exchange,提问作者paper123

