触发不同容器中多个选择框的相同功能

时间:2017-03-30 07:01:04

标签: jquery

我在多个div中选择了一个框,它显示了span div中所选的选项值。 jquery函数仅对第一个div选择框执行,而不对其余部分执行。我想要一个适用于所有div的单一函数,而不需要为每个div重复代码。

<div class="format-block">
  <span class="format-title">Format:</span>
  <select id="format3" class="selectpicker" name="for" >
    <option value="48.00" selected="selected">Paperback</option>
    <option value="40.00">eBook</option>
  </select>                                    
  <span id="price-div3" >
    <span class="price"></span>
  </span> 
</div>

<div class="format-block">
  <span class="format-title">Format:</span>
  <select id="format4" class="selectpicker" name="for" >
    <option value="48.00" selected="selected">Paperback</option>
    <option value="40.00">eBook</option>
  </select>
  <span id="price-div4">
    <span class="price"></span>
  </span> 
</div>
$(document).ready(function() {      
  var format_div = $(".format-block select").attr("id");
  $(".format-block span.price").html("£" + $("#" + format_div).val());

  $('.format-block').on("change", "select", function() { 
    $(".format-block span.price").html("£" + $("#" + format_div).val());
  });
});
请告诉我这里我做错了什么..

1 个答案:

答案 0 :(得分:0)

您需要使用event.target,即启动该事件的DOM元素。您需要在其上下文中执行操作。

&#13;
&#13;
$('.format-block').on("change", "select", function(event) {
  $(event.target).closest(".format-block").find("span.price").html("£" + $(event.target).val());
});

//Tigger event handler, to set the price
$('.format-block select').trigger('change');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="format-block">
  <span class="format-title">Format:</span>
  <select id="format3" class="selectpicker" name="for">
    <option value="48.00" selected>Paperback</option>
    <option value="40.00">eBook</option>
  </select>
  <span id="price-div3">
    <span class="price"></span>
  </span>
</div>

<div class="format-block">
  <span class="format-title">Format:</span>
  <select id="format4" class="selectpicker" name="for">
    <option value="48.00">Paperback</option>
    <option value="40.00" selected>eBook</option>
  </select>
  <span id="price-div4">
    <span class="price"></span>
  </span>
</div>
&#13;
&#13;
&#13;

参考

  1. .closest()
  2. .find()
  3. .trigger()