2016-11-24 6 views
-1

のdivのid をクリックしますfuncは、このIDの代わりに "#のdropdown1"はどのようにdivのIDを取得し、anoher FUNCに設定する

$(function() { 



    $('.drop-down-input').click(function() { 

     $elementid = this.id; 
     $elementid= "#" + elementid; 
    }); 
     console.log($elementid); 
    $("#dropdown1").click(function() { 

     $("#dropdown1 .dropdown-list").show(); 

    }); 

    $("#dropdown1 .dropdown-list li").on('click', function(e) { 
    e.stopPropagation(); 
    $("#dropdown1 .dropdown-list").hide().siblings().val($(this).html()); 
    }); 
}); 

HTML FUNC次与える必要が持っている:

<div id="dropdown1" class="styled-input-container drop-down-input"> 
        <input id="simple_2" class="drop-down-select" placeholder="input text" type="text"> 
        <ul class="dropdown-list"> 
         <li>eeee</li> 
         <li>xxxx</li> 
         <li>xxxx</li> 
         <li>xsssxxx</li> 
        </ul> 
       </div> 

アイデアは私が別の場所でこのコードを使用することができるということです。異なるIDを持つ2つのドロップダウンを使用する

+0

はあなたが達成したいんどのようなグローバル変数 – Mahi

+0

作りますか?これは悪い方法のように思えます。 – Mihailo

+0

キャッチされていないReferenceError:何もクリックしないとelementidが定義されていません(...) –

答えて

0

IDを送信しないで、要素にクラスを追加します。

$('.drop-down-input').click(function() { 
    $('.drop-down-input.selected').removeClass('selected'); // Forget the previous selection 
    $(this).addClass('selected'); 
    $(this).find(".dropdown-list").show(); 
}); 

は、その後、次の関数の中で、あなたがクリックした要素を見つけるために、セレクタを使用することができます。

$(document).on("click", ".drop-down-input.selected li"), function(e) { 
    e.stopPropagation(); 
    $('.drop-down-input.selected .dropdown-list').hide().siblings().val($(this).html()); 
}); 

変数にIDを保存する以上、この方法の利点は、追加するCSSを使用することができるということです選択された要素へのスタイル

全コード:

$('.drop-down-input').click(function() { 
 
    $('.drop-down-input.selected').removeClass('selected'); // Forget the previous selection 
 
    $(this).addClass('selected'); 
 
    $(this).find(".dropdown-list").show(); 
 
}); 
 

 
$(document).on("click", ".drop-down-input.selected li", 
 
    function(e) { 
 
    e.stopPropagation(); 
 
    $('.drop-down-input.selected .dropdown-list').hide().siblings().val($(this).html()); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="dropdown1" class="styled-input-container drop-down-input"> 
 
    <input id="simple_2" class="drop-down-select" placeholder="input text" type="text"> 
 
    <ul class="dropdown-list"> 
 
    <li>eeee</li> 
 
    <li>xxxx</li> 
 
    <li>xxxx</li> 
 
    <li>xsssxxx</li> 
 
    </ul> 
 
</div>

+0

をチェックしてください。私はドロップダウンを2,3回使用したいと考えています。 div idで区切りたいのです –

+0

これはなぜ機能しませんか?クラスごとに要素を選択することは、変数を使用してIDを保持するのと同じくらい効果的です。 – Barmar

+0

$( "#dropdown1") - 削除する必要があります。そのIDはクリックされた要素から取得します。 –

関連する問題