相关疑难解决方法(0)

当我使用val()设置select的值时,为什么jquery更改事件不会触发?

change()当值设置时,事件处理程序中的逻辑不会运行val(),但它会在用户使用鼠标选择值时运行.为什么是这样?

<select id="single">
    <option>Single</option>
    <option>Single2</option>
</select>

<script>
    $(function() {
        $(":input#single").change(function() {
           /* Logic here does not execute when val() is used */
        });
    });

    $("#single").val("Single2");
</script>
Run Code Online (Sandbox Code Playgroud)

html jquery select input

370
推荐指数
5
解决办法
24万
查看次数

如何以编程方式单击“选择”元素并触发onChange处理程序?

例如,使用以下代码。我尝试了几种解决方案。

function handleChange() {
    alert('hello')
}

<select id="names" onchange="handleChange()">
    <option>Foo</option>
    <option>Bar</option>
</select>
Run Code Online (Sandbox Code Playgroud)

解决方案1。

document.getElementById('#select').selectedIndex = 1
Run Code Online (Sandbox Code Playgroud)

这将更改select的值和显示,但不会触发handleChange();。

解决方案2

var element = document.getElementById('names');
var event = new Event('change');
element.dispatchEvent(event);
Run Code Online (Sandbox Code Playgroud)

这返回true,但仍然不会触发handleChange();。


有关如何执行此操作的任何想法?还是可以实际完成?解决方案必须仅是javascript / html,而遗憾的是没有jQuery。

html javascript

3
推荐指数
1
解决办法
5118
查看次数

标签 统计

html ×2

input ×1

javascript ×1

jquery ×1

select ×1