簡體   English   中英

如何在jQuery中將這種單一情況(顯示基於下拉列表的選擇顯示文本字段)抽象為通用函數?

[英]How to abstract this single case (showing text field based on selection of a drop down list) into a general function in jQuery?

這是我關於SO的第一個詳細問題。

嗨,我有一個表單,並且有很多實例,當用戶在下拉列表中選擇“其他”選項時,我想在下拉列表后顯示一個文本字段。

我正在使用標准的命名約定,並且想知道,我是否必須具有與文檔中的DDL /文本字段對一樣多的功能,或者我可以擁有可以調用一類DDL的單個功能? 這是HTML:

<label for="spotter">Spotter:</label>
<select id="spotter" required>
    <option value="Snoop Dogg">Snoop Dogg</option>
    <option value="MC Escher">MC Escher</option>
    <option value="Linus Thorvalds">Linus Thorvalds</option>
    <option value="Other">Other</option>
</select>
<br/>

<div id="spotter_other_div"><label for="spotter_other">Other Spotter:</label><br><input type="text" name="spotter_other" id="spotter_other" size="50" required/></div>

這是jQuery / javascript:

$(document).ready(function(){   
    $("#spotter").change(function () {
        //alert("You just changed the value of the #spotter drop down menu.");
        if ($(this).val() == "Other" )
            //alert("You just changed the value of the #spotter drop down menu to 'Other.'");
            $("#spotter_other_div").css("visibility", "visible");
        else
            $("#spotter_other_div").css("visibility", "collapse");
    });     
});

包含文本字段的div的初始狀態為CSS中的“折疊”。

我正在學習jQuery,現在我知道如何為一般情況做一些事情,我想看看這是否是我可以編寫的函數,或者是否必須明確地做。

請注意,該頁面正在進行中,因此歡迎您提出任何建議(例如,使用范圍而不是使用div來包含文本字段等)。

謝謝!

您可以只將一個函數與某些代碼一起使用,然后多次調用(或者,如果您使用相同的idclass則調用一次)...因此,函數的用途:可重用的代碼位。 這是它的外觀。

$(function () { //shorthand for ready in jQuery
    //set up your function
    function dropDownOther(spotter, spotterDiv) { //function takes two args
        $(spotter).change(function () {
            if ($(this).val() == "Other") {
                $(spotterDiv).css("visibility", "visible");
            } else {
                $(spotterDiv).css("visibility", "collapse");
            }
        });
    }
    dropDownOther("#spotter", "#spotter_other_div"); //call your function
    dropDownOther("#otherSelector", "#otherSelectorTwo"); //call it again if necessary 
});

我在這里看到兩個選擇。

  1. 創建一個函數並將其參數化。 這就是Sethen Maleno的答案所顯示的。
  2. 使您的功能更通用。

例如:

$(document).ready(function(){   
    // Apply this to every select element
    $("select").change(function () {
        // Dynamically build up the selector to show/hide
        var secondMenuId = '#' + $(this).attr(id) + '_other_div'
        if ($(this).val() == "Other" )
            $(secondMenuId).css("visibility", "visible");
        else
            $(secondMenuId).css("visibility", "collapse");
    });     
});

請注意,這種方法在生成HTML時需要紀律,並且對id進行了適當的分配(自從您提到使用標准命名約定以來,您似乎正在這樣做)。

這種方法的優勢在於,這是您唯一的代碼,無需編寫大量處理程序。

Sethen為您提供了更多的靈活性,因為您的id不需要遵循嚴格的約定(您可以將所需的任何參數作為參數傳遞),但是確實需要您編寫函數調用才能將其附加到所需的每個項目上。

兩種技術都是有效的,並有其時間和地點。

暫無
暫無

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

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