简体   繁体   English

jQuery的。 检查选项元素是否已选择属性

[英]jQuery. Check if the option element has selected attribute

I have a function that needs to be fired on window load only if there on page is no option elements that has "selected" attribute. 我有一个仅在页面上没有具有“ selected”属性的选项元素时才需要在窗口加载时触发的函数。

<option value="1" selected="selected">Option</option>

I tried to do this with no luck with next function: 我试图通过下一个函数来做到这一点没有运气:

function fireWhenLoad () 
{
if ( $('select option').is(':selected')) {
        alert("Selected");
    }
    else
    {
        alert("Not Selected");
        runIfNoSelectedOptions();
    }
};

$(window).load(function(){
    fireWhenLoad();
});

The function alerts "Selected" in every case if options has "selected" attribute and if they don't. 如果选项具有“已选择”属性,则该功能会在每种情况下提醒“已选择”。

So what am I doing wrong and how can I check if option element has "selected" attribute? 那么,我在做什么错了,如何检查选项元素是否具有“ selected”属性?

Thank you! 谢谢!

您可以使用JQuery的$.(document).ready()功能来触发事件。

If I understand you correctly, Use $(document).ready() to enure dom elements have been loaded and then loop through the options. 如果我对您的理解正确,请使用$(document).ready()确保dom元素已加载,然后遍历选项。 You are currently only selecting first option. 您目前仅选择第一个选项。

$(document).ready(function(){
$("select option").each(function() {
var $this = $(this);
    if ($this.attr("selected") !== undefined) {
        alert("Selected");
    }
    else
    {
        alert("Not Selected");
        runIfNoSelectedOptions();
        return false;
    }
});

}); });

Have you tried, 你有没有尝试过,

$('option').each(function(){
    if($(this).is(':selected')){
       alert("Selected");
    }
    else
    {
        alert("Not Selected");
        runIfNoSelectedOptions();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM