如何使用Jquery处理作为按钮实现的下拉列表

时间:2017-08-24 05:23:50

标签: javascript jquery

<div class="btn-group btn-grp-uk col-xs-12 ">
    <button id="colorList" type="button" class="btn-phn btn btn-dropdown-white-
    uk dropdown-toggle col-xs-12" data-toggle="dropdown">Red
    </button>
      <ul id="colordrop" class="dropdown-menu col-xs-12 p-l-0">
        <sly data-sly-list.color="${modelobj.list}">
          <li>${color}</li>
        </sly>
      </ul>
</div>
<div>
<p><strong>MONTHLY COST</strong></p>
<h3 id="monthly-price">£35<small>.00</small></h3>
</div>

当选择下拉值中的值时,我需要帮助更改标签中的价格。由于下拉列表是作为一个我无法改变的按钮实现的,有人可以帮助我实现这一目标。

我试过这个,但它是在第一次点击按钮本身而不是下拉值时发生的。我试图在第二次点击时获得事件触发器,因为第一次点击将打开下拉列表,第二次点击负责从下拉列表中选择选项。

**var count=0;
$( "#colordrop" ).click(function(event){   
    count++;
    if(count%2==0)      
    var colorListData = document.getElementById("colordrop").innerHTML; 
    document.getElementById('monthly-price').innerHTML = colorListData;
});**

实际的HTML是:

<div class="btn-group btn-grp-uk col-xs-12 ">
    <button type="button" class="btn-phn btn btn-dropdown-white-uk dropdown-toggle col-xs-12" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Default Color <span class="glyphicon glyphicon-menu-down"></span> <span class="glyphicon glyphicon-menu-up"></span>
    </button>
    <ul class="dropdown-menu col-xs-12 p-l-0">
        <li> <a href="#">Color1</a> </li>
        <li> <a href="#">Color2</a> </li>
        <li> <a href="#">Color3</a> </li>       
        <li> <a href="#">Color4</a> </li>
    </ul>
</div>
<div class="col-xs-12 col-md-8 col-md-offset-4 text-center ">
    <div class="col-xs-6 col-sm-4 col-sm-offset-2 col-md-3 col-md-offset-0 mob-cost">
    <p><strong>MONTHLY COST FROM</strong> </p>
    <h3>&pound;35<small>.00</small></h3> </div>
</div>

1 个答案:

答案 0 :(得分:1)

您需要处理每个<li>的点击,而不是<ul>。我还在您的HTML中注意到您错过了<ul>上的ID,因此请务必添加该ID。

&#13;
&#13;
$("#colordrop > li").click(function(event){
  var colorListData = $(this).text(); 
  console.log(colorListData);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group btn-grp-uk col-xs-12 ">
    <button type="button" class="btn-phn btn btn-dropdown-white-uk dropdown-toggle col-xs-12" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Default Color <span class="glyphicon glyphicon-menu-down"></span> <span class="glyphicon glyphicon-menu-up"></span>
    </button>
    <ul id="colordrop" class="dropdown-menu col-xs-12 p-l-0">
        <li> <a href="#">Color1</a> </li>
        <li> <a href="#">Color2</a> </li>
        <li> <a href="#">Color3</a> </li>       
        <li> <a href="#">Color4</a> </li>
    </ul>
</div>
<div class="col-xs-12 col-md-8 col-md-offset-4 text-center ">
    <div class="col-xs-6 col-sm-4 col-sm-offset-2 col-md-3 col-md-offset-0 mob-cost">
    <p><strong>MONTHLY COST FROM</strong> </p>
    <h3>&pound;35<small>.00</small></h3> </div>
</div>
&#13;
&#13;
&#13;

JSFiddle:https://jsfiddle.net/bf43v8vy/