2016-06-08 2 views
1

<li>에 부트 스트랩 드롭 다운을 추가했습니다. 이 드롭 다운 안에 다른 ID와 텍스트가있는 두 개의 옵션 <li>이 있습니다. 두 개의 선택 항목 중 어떤 것이 선택되었는지에 따라 드롭 다운의 텍스트를 변경할 수 있기를 원합니다.클릭시 부트 스트랩 드롭 다운의 색상 및 텍스트 변경

<ul> 
    <li class="listItem"> 
    <h5>Item Header</h5> 
    <div class='dropdown'> 
     <button id='flagchoice' class='btn btn-default dropdown-toggle' type='button' data-toggle='dropdown'>Category<span class='caret'></span></button> 
     <ul class='dropdown-menu dropdown-menu-right'> 
     <li id='choice1'>Choice 1</li> 
     <li id='choice2'>Choice 2</li> 
     </ul> 
    </div> 
    </li> 
</ul> 

제가 작성한 것을 설명하기 위해 JSFiddle을 작성했습니다.

선택한 드롭 다운 옵션의 텍스트, 색상 및 배경색을 사용하고 싶습니다.

은 내가 드롭 다운의 또 다른 경우에 유사하게 사용했습니다 어떤이를 사용하여 시도하지만,이 경우에는 작동하지 않습니다

$(".dropdown-menu li#choice1").click(function(){ 
    $(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>'); 
    $(this).parents(".dropdown").find('.btn').val($(this).data('value')); 
}); 

$(".dropdown-menu li#choice2").click(function(){ 
    $(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>'); 
    $(this).parents(".dropdown").find('.btn').val($(this).data('value')); 
}); 

EDIT1 :

내가 깜빡 추측 언급 한 것과 마찬가지로 JSFiddle에서 'ListItem '은 자바 스크립트 코드를 사용하여 동적으로 추가되고 드롭 다운의 선택 항목은 다양합니다.

답변

1

jQuery 코드가 제대로 작동했습니다. 두 번의 클릭 핸들러가 필요 없도록 수정했지만 다시 되돌릴 수는 있습니다. 여기

$(document).ready(function() { 
     $(".dropdown-menu li").click(function(){ 
      var color = $(this).css("color"); 
      var bgColor = $(this).css("background-color"); 
      var parent = $(this).parents(".dropdown").find('.dropdown-toggle'); 
      parent.html($(this).text() + ' <span class="caret"></span>'); 
      parent.val($(this).data('value')); 
      parent.css({"background-color" : bgColor, "color" : color}); 
     }); 

}); 

내가 클릭 핸들러가 존재하지 않는 메뉴 항목 때문에 문서 자체에 추가 할 수있다 동적으로 추가 요소를 처리하기 위해
https://jsfiddle.net/q79fpua4/2/

편집
을 만든 JSFiddle입니다 문서가 처음로드 될 때 이것은 트릭을해야합니다.

$(document).ready(function() { 
     $(document).on("click", ".dropdown-menu li", function(){ 
      var color = $(this).css("color"); 
      var bgColor = $(this).css("background-color"); 
      var parent = $(this).parents(".dropdown").find('.dropdown-toggle'); 
      parent.html($(this).text() + ' <span class="caret"></span>'); 
      parent.val($(this).data('value')); 
      parent.css({"background-color" : bgColor, "color" : color}); 
     }); 
}); 
+0

나는 이것을 사용해 보았지만, 제 경우에는 효과가없는 것 같습니다. 내가 listItem을 동적으로 추가한다는 사실과 관련이 있는지 나는 모른다. – Zeliax

+0

@ Zeliax yup 요소를 동적으로 추가하면 약간 변경됩니다. 나는 그 사건을 다루기 위해 나의 대답을 업데이트했다. – StaticBeagle

관련 문제