简体   繁体   English

使用 JS/JQuery 从附加的选择器选项中获取值

[英]Get the value from an appended selector option using JS/JQuery

I'm trying to get the value from an appended selector with a JQuery function.我正在尝试从带有 JQuery 函数的附加选择器中获取值。 The function works well with the main element, that was not appended, but does nothing with the appended ones.该函数适用于未附加的主要元素,但对附加的元素没有任何作用。

My code:我的代码:

<div id="mainSeparator">
      <div id="newLayer" class="newLayer">        
        <div class="form-row">
          <div class="form-group col-md-6">
            <select class="form-control mySelector" id="selector">
              <option hidden disabled selected value>Select an option</option>
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
            </select>
          </div>
        </div>
        <div class="newDiv"></div>
      </div>      
    </div>

The function I'm using now for get the values:我现在用于获取值的函数:

$(document).on('change', '.mySelector', function () {
      var str = "";
      $('.mySelector option:selected').each(function () {
        str += $( this ).text();
        $('.newDiv').text(str);
      })
    });

The issue is because you always target $('.mySelector option:selected') .问题是因为您总是以$('.mySelector option:selected') This will only ever look at the first instance of the .mySelector element in the DOM.这只会查看 DOM 中.mySelector元素的第一个实例。

From the context of the logic it appears that you want to look at the selected options within the select that raised the change event.从逻辑的背景下看来,你想看看选择的选项select ,所提出的change情况。 As such you need to use this and find() .因此,您需要使用thisfind() Also note that it would make more sense to update .newDiv once after the loop completes:另请注意,在循环完成后更新.newDiv会更有意义:

$(document).on('change', '.mySelector', function () {
  var str = "";
  $(this).find('option:selected').each(function () {
    str += $(this).text();
  });
  $('.newDiv').text(str);
});

The logic could also be made more slightly succinct by using map() :还可以使用map()使逻辑更加简洁:

$(document).on('change', '.mySelector', function () {
  var str = $(this).find('option:selected').map(function () {
    return $(this).text();
  }).get().join('');
  $('.newDiv').text(str);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM