【问题标题】:Check if some attr are checked with jquery on load检查是否在加载时使用 jquery 检查了某些属性
【发布时间】:2013-03-11 16:05:53
【问题描述】:

我想检查是否在加载时检查了我的 html 选择中的 3 个选项中的 2 个细节。

其实,我的 HTML :

<select name="country" id="country" tabindex="7" style="width:128px; margin-right:26px;">
            <option selected="selected" name="0">Choisir...</option>
            <option value="Canada" <?php if($pays == 'Canada'){echo "selected=selected";} ?>>Canada</option>
            <option value="États-Unis" <?php if($state == 'États-Unis'){echo "selected=selected";} ?>>États-Unis</option>
        </select>

我的 jQuery 如下:

if($('#reference').attr('selected',true))
    {
        $('.showDetaillant').show();
    }

如您所见,它只检查是否“选中”了某些内容。默认情况下,这是选项“Choisir...”。

如果选择了“Choisir...”选项,我想要设置 .hide()。

谢谢

【问题讨论】:

  • 顺便说一句,选项字段不能有名称。

标签: jquery selectedvalue


【解决方案1】:

您可以使用selectedIndex属性,如果您想在页面加载时检查选择的选项,您可以在DOMReady上触发change事件。

$('#country').change(function(){
    if (this.selectedIndex === 0) {
        $('.showDetaillant').show();
    }
}).change();

http://jsfiddle.net/JfDZ4/

PS:请注意,您使用 attr 作为 setter,它返回一个始终被评估为 true 的 jQuery 对象。

【讨论】:

  • 你能解释一下吗?为什么 change() 是两次?
  • 我会试试这个。它似乎做了我在 jsfiddle 中寻找的东西。
【解决方案2】:
    <select name="country" id="country" tabindex="7" style="width:128px; margin-
        right:26px;">
             <option selected="selected" value="0">Choisir...</option>
     </select>

<script>
     $(document).ready(function () {

         if($('#country').val()=="0")
           $('.showDetaillant').show();
       });

<script>

【讨论】:

  • 我想我有点睡着了。真正的答案是@PSR,但 undefined 也不错,我会在其他地方使用它!
【解决方案3】:

您可以尝试以下方法,它会为您提供所选选项的索引

$("select#elem").get(0).selectedIndex > 0

阅读此How to check if selected index of dropdownlist is not 0 or -1 using jquery

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    相关资源
    最近更新 更多