如何遍历多个选择的多个选项?

How to iterate through multiple options of a multiple selects?

我知道如何遍历一个 select 框的多个选项:

$("#selectId > option").each(function() {
alert(this.text + ' ' + this.value);
});

但是,我将如何遍历一个特定 class 的所有 select 框,然后遍历其所有选项。我想使用 $(this).

这是我目前能做的,显然行不通。

$('.mappingSelectField').each(function(){
        var selectName = $(this).attr("name");
        var preselectValue = "";
        $(this('> option')).each(function() { // THIS LINE NEEDS TO BE ADJUSTED
            if ($(this).val().toLowerCase().replace(/ /g, '') == selectName.toLowerCase().replace(/ /g, '')){
                preselectValue = $(this).val();
            }
        });
        $(this).val(preselectValue);
    });

我只想预先 select 一个合适的选项,该选项与 select 框名称具有相同的值。

您在每个 select 元素迭代中找到错误的 selector 选项元素。

您使用过:$(this('> option'))

这是不正确的。您需要使用 find selector 在当前 select 上下文 this 中查找选项元素。您需要使用:

 $(this).find('option').each(function() { //iterate over options in current select
  //rest code.
 });

  $('option',this).each(function() { //iterate over options in current select
  //rest code.
 });