You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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--location class
  • The element follows MDC Select's required DOM structure (it needs child elements like .mdc-select__anchor and .mdc-select__menu)
  • Your code runs after the DOM is fully loaded (wrap it in a DOMContentLoaded listener 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:46:27