触发单击单选按钮作为文档准备的一部分
Trigger click on radio button as part of document ready
我的应用程序中有一个动态单选按钮列表,在用户做出选择后,我会使用 jQuery 单击功能显示其他内容。这一切都很好,除非单选按钮的动态列表只有一个选项。只有一个选项时,单选按钮本身默认处于选中状态,但除非用户单击单选按钮,否则不会触发单击事件。
有没有一种方法可以在文档准备好时触发点击事件,这样,如果只有一个选项,用户就不必进行多余的点击?
这是我正在使用的 jQuery 代码,同样,只要用户做出选择,它就可以正常工作。
谢谢!
jQuery('input[name="location"]').click(function(){
var data = {location : jQuery(this).val()};
jQuery.ajax({
url: "/custom.php",
type:'POST',
data: data,
dataType: 'html',
success: function(result){
jQuery('#div-custom').html(result).show();
}
});
您可以通过检查 length
属性 来检查您的选择器匹配了多少个单选按钮。如果是,您可以手动触发对该按钮的点击,如下所示:
jQuery(function($) {
var $locations = $('input[name="location"]').click(function(){
$.ajax({
url: "/custom.php",
type:'POST',
data: { location : $(this).val() },
dataType: 'html',
success: function(result) {
$('#div-custom').html(result).show();
}
});
});
if ($locations.length == 1)
$locations.click();
});
另请注意,document.ready 处理程序的第一个参数是对 jQuery 的引用,因此您可以将该变量别名为正常的 $
以避免必须使用冗长的jQuery
无处不在。
我的应用程序中有一个动态单选按钮列表,在用户做出选择后,我会使用 jQuery 单击功能显示其他内容。这一切都很好,除非单选按钮的动态列表只有一个选项。只有一个选项时,单选按钮本身默认处于选中状态,但除非用户单击单选按钮,否则不会触发单击事件。
有没有一种方法可以在文档准备好时触发点击事件,这样,如果只有一个选项,用户就不必进行多余的点击?
这是我正在使用的 jQuery 代码,同样,只要用户做出选择,它就可以正常工作。
谢谢!
jQuery('input[name="location"]').click(function(){
var data = {location : jQuery(this).val()};
jQuery.ajax({
url: "/custom.php",
type:'POST',
data: data,
dataType: 'html',
success: function(result){
jQuery('#div-custom').html(result).show();
}
});
您可以通过检查 length
属性 来检查您的选择器匹配了多少个单选按钮。如果是,您可以手动触发对该按钮的点击,如下所示:
jQuery(function($) {
var $locations = $('input[name="location"]').click(function(){
$.ajax({
url: "/custom.php",
type:'POST',
data: { location : $(this).val() },
dataType: 'html',
success: function(result) {
$('#div-custom').html(result).show();
}
});
});
if ($locations.length == 1)
$locations.click();
});
另请注意,document.ready 处理程序的第一个参数是对 jQuery 的引用,因此您可以将该变量别名为正常的 $
以避免必须使用冗长的jQuery
无处不在。