jQuery事件委托不适用于下拉菜单

时间:2018-08-08 15:34:10

标签: jquery

HTML如下所示:

<div id = 'forecastItems'>
  <select class="ui dropdown categoryScopeItem" id = 'categoryScopeItem1' name = updated[forecastID]>
    <option value=""></option>
    <% items.forEach(function(item) { %>
      <option value = '<%= item.key %>' revenue = '<%= item.totalRevenue %>' releasedValue = '<%= item.releasedvalue %>' percentRemaining = '<%= item.percentRemaining %>' remainingToBill = '<%= item.totalRemaining %>' label = '<%= item.jobNumber %>' style = 'display: none'><%= item.item %></option>
    <% }) %>
  </select>
  <br>
  <div class = 'ui left icon input itemValue' style = 'width: 125px'>
    <input type="text" placeholder="Value" name = updated[value] class = 'ui mini input'>
    <i class = 'dollar sign icon'></i>
  </div>
  <button type = 'button' class = 'newForecastToggle' id = 'firstAdd' style = 'font-size: .8em'>Add More</button>
  <div style = 'display: inline'>
    <span class = 'forecastInfo'></span>
  </div>
</div>
<div id = 'holder'>
  <br>
</div>

我的第一个事件委派工作正常:

$('#scopeItems').on('click', '.newForecastToggle', function(event) {
  event.preventDefault();
  $('#forecastItems').clone().insertBefore($('#holder'))
});

但是,我的第二个事件委托不能正常工作,因此只能在第一个下拉列表中工作:

$('#forecastItems').on('change', 'select', function(e) {
  var itemRevenue = $('.categoryScopeItem :selected').attr('revenue')
  var remainingToBill = $('.categoryScopeItem :selected').attr('remainingToBill')
  var percentRemaining = $('.categoryScopeItem :selected').attr('percentRemaining')
  var releasedValue = $('.categoryScopeItem :selected').attr('releasedValue')

  var selectedItem = $(this).next().next().find('input')
  var valueInfo = $(this).next().next().next().next()

  valueInfo.find('.forecastInfo').text('$' + remainingToBill + ' / $' + itemRevenue + ' (' + percentRemaining + '%) Remaining')

  selectedItem.attr('placeholder', remainingToBill)
})

我认为也许我需要将#forecastItems更改为父元素的id,但是结果是相同的。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

解决方案是更改:

$('.categoryScopeItem :selected').attr('revenue')

$(this).find('option:selected').attr('revenue')

感谢大家在您帮助我获得解决方案时所提供的意见。