jQuery模拟选择选项上的点击事件 [英] jQuery simulate click event on select option

查看:460
本文介绍了jQuery模拟选择选项上的点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个选择菜单,当其中一个选项被点击时触发AJAX请求。我需要从链接中触发相关选项的点击事件。所以我有类似下面的代码,虽然它改变了select的值,它不会模拟一个点击:

I have a select menu that triggers an AJAX request once one of the options has been clicked. I need to trigger a click event on the relevant option from a link. So I have code similar to the below, and although it changes the value of the select, it doesn't simulate a click:

$('#click').click(function(){
    var value = $(this).attr("rel");
    $('#select').val(value);
    return false;
});

<select id="select" name="select">
    <option>Select...</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>

<a href="#" rel="1" id="click">Click for option 1</a>

任何帮助将非常感激。

推荐答案

触发选项上的点击事件将不起作用。这里是一个代码:

Triggering a click event on the option will not work. Here is a code that does:

$('#click').on('click', function(){
    var value = $(this).attr("rel"); //get the value
    value++; //increment value for the nth-child selector to work
    $('#select').find('option:nth-child(' + value + ')').prop('selected',true).trigger('change'); //trigger a change instead of click
    return false;
});

我设置了一个小提琴这里显示相同。
这应该可以工作。

I have setup a fiddle here showing the same. This should work.

而不是使用点击,你可以触发更改事件并达到相同的效果。

Instead of using a click you can trigger the change event and achieve the same effect.

这篇关于jQuery模拟选择选项上的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆