微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在准备好文档时触发一个jQuery change函数

我的更改功能允许用户从国家切换到不同的文字功能。它在改变国家选择时起作用。但是在初始页面加载时,它不会触发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

原文地址:https://www.jb51.cc/jquery/182243.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐