jQuery选择,如果option.value等于某个值,则标记为选中 [英] jquery selection if option.value equal something, mark a selected

查看:723
本文介绍了jQuery选择,如果option.value等于某个值,则标记为选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对jquery选择有一些疑问.在我的情况下,如果option.value等于某项,如何匹配,请为其标记一个selected. 此处在线代码

I have some question about jquery selection. In my case, how to match if the option.value equal something, mark a selected for it. Online code here

再次重复输入代码.它引起了Uncaught TypeError: Object #<HTMLOptionElement> has no method 'val',如何如我所愿?谢谢.

repeat code again. It caused Uncaught TypeError: Object #<HTMLOptionElement> has no method 'val', how to work as my hope? Thanks.

<script type="text/javascript">
$(document).ready(function(){
    var num = 3;
    $("div#selection select.select option").each(function(){
        if((this).val()==num){
            $(this).attr("selected","selected");    
        }
    });
});
</script>
<div id="selection">
    <label>Label1:</label>
    <select class="select">
        <option value="1">V1</option>
        <option value="2">V2</option>
        <option value="3">V3</option>
    </select>
    <label>Label2:</label>
    <select class="select">
        <option value="4">U1</option>
        <option value="5">U2</option>
        <option value="6">U3</option>
    </select>
</div>

推荐答案

您输入了错字

您应该在if语句中使用$(this).val()而不是(this).val(). this引用HTMLObject,$(this)引用jQuery对象.因为.val()方法是jQuery框架的一部分,所以您不能在HTMLObjects上使用它.但我敢肯定,您知道这一点,因为它看起来非常像是一个小错字.

Instead of (this).val() you should use $(this).val() in your if statement. this refers to a HTMLObject, $(this) would refer to a jQuery object. Because the .val() method is part of the jQuery framework, you can't use it on HTMLObjects. But I'm sure you knew that because it looks very much like a small typo.

这应该有效:

$(document).ready(function(){
    var num = 3;
    $("div#selection select.select option").each(function(){
        if($(this).val()==num){ // EDITED THIS LINE
            $(this).attr("selected","selected");    
        }
    });
});


修改

找到元素后,可以添加return false;(对于普通循环为break;)来优化循环,这样在我们已经完成"时它就不会保持循环元素.

You could optimize your loop by adding a return false; (break; for vanilla loops) when you have found your element so it doesn't keep looping elements while we're already "done".

但是,您应该查看 Nicola Peluchetti的答案,以获取更高效,更简洁的代码.

However, you should look at Nicola Peluchetti's answer for a more efficient and cleaner code.

这篇关于jQuery选择,如果option.value等于某个值,则标记为选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆