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

如何动态获取级联下拉框cascadedropdown首个Dropdown的答案值?

级联下拉问题动态获取一级选项值的解决方案

1. 获取一级Dropdown的当前值

在自定义cascadedropdown问题的逻辑中,通过问题实例的getValue()方法或survey模型的getValue()方法,直接获取一级下拉选项的当前选中值。假设一级下拉的字段名为firstLevel:

// 在getSecondLevelChoices方法内获取一级值
const firstLevelValue = this.getValue('firstLevel');
// 或通过survey模型获取
const firstLevelValue = this.survey.getValue('firstLevel');

2. 改造getSecondLevelChoices方法为动态逻辑

将原方法中的固定参数替换为动态获取的一级值,根据不同值返回对应二级选项:

getSecondLevelChoices() {
  const firstVal = this.getValue('firstLevel');
  // 按实际业务逻辑返回对应二级选项
  if (!firstVal) return [];
  
  return {
    'category1': [{value: 'item1', text: '子选项1'}, {value: 'item2', text: '子选项2'}],
    'category2': [{value: 'item3', text: '子选项3'}, {value: 'item4', text: '子选项4'}]
  }[firstVal] || [];
}

3. 监听一级值变化,自动更新二级选项

在自定义问题的初始化代码中,添加一级下拉值变化的监听,触发二级选项刷新:

// 自定义问题类型的构造函数或初始化逻辑中
this.onPropertyChanged.add((sender, options) => {
  if (options.name === 'firstLevel') {
    // 通知二级下拉刷新选项
    this.survey.notifyPropertyChanged('secondLevel');
    // 若使用choicesByUrl,可重新加载
    this.getQuestionByName('secondLevel').choicesByUrl.load();
  }
});

4. 确保SurveyCreator模型配置正确

注册自定义问题时,确保二级下拉的选项配置指向动态方法:

SurveyCreator.CustomQuestionCollection.Instance.add({
  name: 'cascadedropdown',
  title: '级联下拉',
  questionJSON: {
    type: 'cascadedropdown',
    elements: [
      {
        type: 'dropdown',
        name: 'firstLevel',
        title: '一级分类',
        choices: [{value: 'category1', text: '分类1'}, {value: 'category2', text: '分类2'}]
      },
      {
        type: 'dropdown',
        name: 'secondLevel',
        title: '二级选项',
        choicesByUrl: { url: 'javascript:getSecondLevelChoices()' }
      }
    ]
  }
});

内容的提问来源于stack exchange,提问作者LibertyAndHappy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 04:07:04