【问题标题】:find out radio set`s default checked value on page load with jquery使用 jquery 在页面加载时找出单选集的默认检查值
【发布时间】:2015-01-28 04:46:51
【问题描述】:

我编写了一个 jquery 代码,它只是为 div 添加了一个样式。

$('input[type=radio][name=radio-set]').change(function() {
            if (this.id == 'first') {
                $("div.second, div.third").removeAttr('style');
                $("div.first").css({"opacity":"1"});
            }
            else if (this.id == 'second') {
                $("div.first, div.third").removeAttr('style');
                $("div.second").css({"opacity":"1"});
            }
            else if (this.id == 'third') {
                $("div.first, div.second").removeAttr('style');
                $("div.third").css({"opacity":"1"});
            }

        });

<input id="first" type="radio" name="radio-set" checked="checked"/>
<input id="second" type="radio" name="radio-set" />
<input id="third" type="radio" name="radio-set" />

<div class="first">Test Text</div>
<div class="second">Test Text 2</div>
<div class="third">Test Text 3</div>

如何检查默认选中的单选按钮以在页面加载时向其相关 div 添加样式?!我在 jquery 代码的末尾添加了change(),但由于默认选中的属性位于带有#first id 的按钮上,因此它选择了带有.third 类的div。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    我通常通过在元素上调用 .trigger('change') 来做到这一点:

    $('input[type=radio][name=radio-set]').change(function() {
        // lots of code here
    }).trigger('change');
    

    不要忘记在 DOM 准备好后调用你的函数。

    编辑:抱歉,我没有仔细阅读您的问题。在您的情况下,您应该只在选中的收音机上触发更改:.filter(':checked').trigger('change');

    【讨论】:

    • 我做了同样的事情,当然只是简单地添加了 .change();但是,正如我提到的,它为具有 (#first) id 的按钮选择了错误的 div(第三个)
    【解决方案2】:

    如果您只希望代码在 DOM 准备好后运行,您可以执行以下操作:

    var selectedInput = $('input[name="radio-set"]:checked').attr('id');
    $('div.' + selectedInput).addClass('whatever_style_you_want');
    

    显然addClass 可以更改为反映css 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      相关资源
      最近更新 更多