簡體   English   中英

同時打開兩個下拉菜單的問題

[英]Issue in opening two dropdown at same time

這里id下拉小提琴http://jsfiddle.net/ym8t7Lhj/

我面臨的問題是我有兩個下拉菜單,如果我單擊一個下拉菜單,另一個下拉菜單也會打開。 誰能幫我這個忙。

腳本

        $(document).ready(function() {
        $(".dropdown dt a").click(function() {
        $(this).toggleClass("myclass"); 
         $(".dropdown dd ul").toggle();
         });

        $(".dropdown dd ul li a").click(function() {

            var text = $(this).html();
            $('.dropdown dt a').toggleClass('myclass');
            $(".dropdown dt a span").html(text);
            $(".dropdown dd ul").hide();
            $("#result").html("Selected value is: " + getSelectedValue("sample"));
        });      
    });

像這樣更改您的代碼,

$(document).ready(function() {
    $(".dropdown dt a").click(function() {
        $(this).toggleClass("myclass");
        $(this).closest(".dropdown").find("dd ul").toggle();
    });

    $(".dropdown dd ul li a").click(function() {
        var text = $(this).html();
        var parent = $(this).closest(".dropdown");
        parent.find("dd ul").toggle();
        parent.find('dt a').toggleClass('myclass');
        parent.find("dt a span").html(text);
        parent.find('dt ul').hide();
        $("#result").html("Selected value is: " + getSelectedValue("sample"));
    });
});

注意:相對於單擊的元素切換元素。

更新小提琴

嘗試這個

$(document).ready(function() {
 $(".dropdown dt a").click(function() {
        $(this).toggleClass("myclass"); 
         $(this).closest('dl').find('ul').toggle();
 });

 $(".dropdown dd ul li a").click(function() {

            var text = $(this).html();
             $(this).closest('dl').find('dt a').toggleClass('myclass').find('span').html(text);

            $(this).closest('ul').hide();
            $("#result").html("Selected value is: " + getSelectedValue("sample"));
  });      
});

替換(".dropdown dd ul").toggle(); 具有以下內容:

$(this).parent().next().find("ul").toggle();

完整代碼:

       $(document).ready(function() {
          $(".dropdown dt a").click(function() {
             $(this).toggleClass("myclass");    
             $(this).parent().next().find("ul").toggle();
          });

            $(".dropdown dd ul li a").click(function() {

                var text = $(this).html();
                var thisRoot = $(this).closest('.dropdown');
                thisRoot.find('dt a').toggleClass('myclass');
                thisRoot.find("dt a span").html(text);
                thisRoot.find("dd ul").hide();
                $("#result").html("Selected value is: " + getSelectedValue("sample"));
            });      
        });

您正在使用相同的選擇器進行下拉。 嘗試在其上添加ID,然后使用$('dropdown1')和$('dropdown2')

[Working Code][1]


  [1]: http://jsfiddle.net/ym8t7Lhj/5/

請勿對每個ID使用ID。 只有您必須記住通過$(this)訪問onclick元素。

因此,它將只給您元素。沒有其他具有相同類的元素。

暫無
暫無

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

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