【问题标题】:auto select dropdown list with javascript and run jquery使用 javascript 自动选择下拉列表并运行 jquery
【发布时间】:2017-06-16 22:54:41
【问题描述】:

在 html 页面中,我们有 2 个下拉列表,当我们从第一个 jquery 工作中提取一些东西并为下一个下拉列表显示更多选项时,这是一个 html 代码:

            <select name="cat_level1" id="cat_level1" size="1" class="form-control input-inline">
                <option value="0">1</option>
                <option value="8">2</option>
                <option value="6">3</option>    
            </select>
            <select name="cat_level2" id="cat_level2" size="1" class="form-control input-inline">
                <option value="0">-</option>
            </select>

            <script>
            $("#cat_level2").chained("#cat_level1");
            </script>

现在我尝试使用 javascript 从我的 win 应用程序中以编程方式选择下拉列表选项,我使用此代码进行选择:

        var len = element.options.length;
        for (int i = 0; i < len; i++)
        {
            if (element.options[i].value == selected_val)
            {
                element.options[i].selected = true;
                break; ;
            }
        }

这行得通,但使用该代码 jquery 不起作用,我们在 secend dropdownlist 中没有任何选项。 选择后如何选择运行该 jquery 的选项?

【问题讨论】:

  • 这和c#有什么关系?
  • link
  • 我在 C# 的 awesomium 浏览器中使用该 javascript 代码

标签: javascript c# jquery html autocomplete


【解决方案1】:

当通过代码选择选项时,没有触发事件,这可能是第二次选择没有更新的原因。

int 使用 var 会出错。通过代码以及使用element.dispatchEvent 触发更改事件。

var len = element.options.length;
for (var i = 0; i < len; i++)
{
     if (element.options[i].value == selected_val)
     {
         element.options[i].selected = true;
         var event = new Event('change');
         element.dispatchEvent(event);
         break; ;
     }
}

您还需要从更改事件处理程序中调用链式函数。

$("#cat_level1").on("change", function(){
   $("#cat_level2").chained("#cat_level1");
});

【讨论】:

  • 谢谢,我尝试使用您的代码,但我没有任何选择!
  • 你订阅了 change 事件吗?您是否从更改事件处理程序中调用链式函数?请查看我的更新答案。
【解决方案2】:

你为什么不试试这个?

$('yourSelect').find('option[value='+selected_val+']').attr('selected', true);

编辑:没有 jQuery

    var len = element.options.length;
    for (int i = 0; i < len; i++)
    {
        if (element.options[i].value == selected_val)
        {
            //element.options[i].selected = true;
            element.options[i].setAttribute('value',true);
            break;
        }
    }

【讨论】:

  • 我无法在 Windows 应用程序中执行 jquery,我只能从 javascript 代码中使用
猜你喜欢
  • 1970-01-01
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多