jQuery jQuery模拟选择选项上的点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15549975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery simulate click event on select option
提问by Stuart Taylor-Jones
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:
我有一个选择菜单,一旦单击其中一个选项,就会触发 AJAX 请求。我需要从链接触发相关选项的点击事件。所以我有类似于下面的代码,虽然它改变了选择的值,但它不模拟点击:
$('#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>
Any help would be greatly appreciated.
任何帮助将不胜感激。
回答by Larrydx
Triggering a click event on the option will not work. Here is a snippet 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 hereshowing the same. This should work.
Instead of using a click you can trigger the change event and achieve the same effect.
您可以触发更改事件并实现相同的效果,而不是使用单击。
回答by Brad M
$('#click').click(function(){
var value = $(this).attr("rel");
$('#select')
.val(value)
.trigger('click');
return false;
});
Merely setting the value of a <select>
does not trigger the click event of that element; it must be called directly.
仅仅设置 a 的值<select>
不会触发该元素的点击事件;必须直接调用。
回答by Stuart Taylor-Jones
It's part of WooCommerce core, so I cannot post all of it. But here is a snippet although I am not too sure if it will tell you much...
它是 WooCommerce 核心的一部分,因此我无法发布所有内容。但这是一个片段,虽然我不太确定它是否会告诉你很多......
.on( 'change', '.variations select', function( event ) {
$variation_form = $(this).closest('form.variations_form');
$variation_form.find('input[name=variation_id]').val('').change();
$variation_form
.trigger( 'woocommerce_variation_select_change' )
.trigger( 'check_variations', [ '', false ] );
$(this).blur();
if( $().uniform && $.isFunction( $.uniform.update ) ) {
$.uniform.update();
}
} )