簡體   English   中英

jQuery選擇下拉選項,只有一個非空白選項

[英]jQuery select dropdown option with only one non-blank option

我正在處理店面包(所以我沒有編輯核心文件的選項),我們有下拉菜單來選擇用戶想要名片的正面和背面。 有些卡只有一個選項,因此如果只有一個選項,客戶端會隱藏下拉菜單。

容易,對嗎?

$("select").each(function(){
    var count = $(this).children("option").length;
    if ( count == 1 ) {
        // there's only one option, do something
    }
});

這是有效的,但問題是系統有時會為某些下拉列表生成一個空白<option> ,所以實際上有兩個選項,但只有一個“真實”選項:

<select>
    <option></option>
    <option value="Something">A real option</option>
</select>

基本上,我需要選擇只有一個<option>或兩個<option><select> s,其中一個只是空的。

我無法完全理解這種if語句的邏輯,所以如果有人有任何建議,我將不勝感激。

你可以使用not method和:empty selector:

$("select").each(function(){
    var count = $(this).find("option").not(':empty').length;
    if ( count == 1 ) {
        alert('okay')
    }
});

DEMO

改變你計算它們的方式:

$('select').each(function() {
    var count = 0;
    $(this).children('option').each(function() {
        if ( $(this).text() ) // true if not empty
        {
            ++count;
        }
    });
    if ( count == 1 ) // count only includes non-empty options

那應該處理它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM