我的更改功能允许用户从国家切换到不同的文字和功能。它在改变国家选择时起作用。但是在初始页面加载时,它不会触发jQuery更改以设置隐藏并显示默认/初始国家/地区的文本div。
两个div都会在初始页面加载时显示。当我改变,然后回到默认/初始国家,更改火灾,隐藏和显示火灾,并显示正确的信息和功能。
我已经在switch选项内部和change函数之外尝试了用document.ready和change功能。无论是工作,他们都不会在开关箱中触发隐藏,显示和其他jQuery。对我来说,“准备”是否是一个有效的触发事件,并不清楚。
我也试过:
$('input[name=country]').value('US').trigger('click');
但它打破了变化的功能。这是代码。下面的国家选择只是两个国家保持简单,但实际上有很多。
$(document).ready(function()
{
//1st tier - select country via radio buttons:
//Initialize country
$('input[name=country]:first').attr('checked',true); //Set first radio button (United States)
//$('input[name=country]:first').attr('checked',true).trigger('ready'); //sets 1st button,but does not fire change
//$('input[name=country]:first').trigger('click'); //sets 1st button,but does not fire change
$('input[name=country]').change(function ()
{
// change user instructions to be country specific
switch ($('input[name=country]:checked').val())
{
case 'US':
$('#stateMessage1').text('2. Select a state or territory of the United States.');
$('#stateMessage2').text('Start typing a state of the United States,then click on it in the dropdown Box.');
$('#threeSelects').show();
$('#twoSelects').hide();
//select via 3 steps
break;
case 'CA':
$('#stateMessage1').text('2. Select a province or territory of Canada.');
$('#stateMessage2').text('Start typing a province of Canada,then click on it in the dropdown Box.');
$('#twoSelects').show();
$('#threeSelects').hide();
//select town via 2 steps - country,town
break;
}
});
});
解决方法
只需将.trigger(‘change’)链接到处理程序分配的结尾。
// ----------v-------v-----quotation marks are mandatory
$('input[name="country"]').change(function ()
{
// change user instructions to be country specific
switch ($('input[name="country"]:checked').val())
{
case 'US':
$('#stateMessage1').text('2. Select a state or territory of the United States.');
$('#stateMessage2').text('Start typing a state of the United States,town
break;
}
}).trigger('change'); // <--- RIGHT HERE
或者如果您只想要在第一个元素上触发,请改用triggerHandler()。
// ...
$('#twoSelects').show();
$('#threeSelects').hide();
//select town via 2 steps - country,town
break;
}
}).triggerHandler('change'); // <--- RIGHT HERE