【问题标题】:Looping to get all elements, where to utilize forEach?循环获取所有元素,在哪里使用 forEach?
【发布时间】:2021-11-02 16:33:31
【问题描述】:

我正在进行网络抓取以返回值,但是我不确定如何输出所有元素。

例如,html 看起来像这样:

<input type="radio" name="code" value="111">
<input type="radio" name="code" value="222">
<input type="radio" name="code" value="333">

我正在尝试输出所有值。

function scrapeValues {
const $codes = $('input[name="code"]');
    for (const code of $codes.get()) {
      const $code = $(code);
      const results = $code.val() as string;
      codeArray = results.trim();
    }
  return codeArray
}

目前,我只得到最后一个值 (333)。我想我需要在某处使用 forEach 但我尝试在 $codes.get() 之后使用它但我收到错误,不确定是因为结束标签位于错误的位置还是我需要在其他地方实现它.

【问题讨论】:

  • 您的所有元素都具有相同的确切名称 soooo....只能选择其中一个...您应该获取以下值:.checked as in.. . 遍历输入并查看是否检查了其中任何一个...如果是...获取元素值...

标签: javascript jquery arrays loops mapping


【解决方案1】:

OP 希望在检索到例如 Array.prototype.map 后使用一个NodeList 通过document.querySelectorAll 哪个,在映射之前,需要一个Array.from

顺便说一句,jquery implements its own map ...

console.log(
  Array.from(
    document.querySelectorAll('[type="radio"][name="code"]')
  ).map(node => node.value)
);
console.log([
  ...document.querySelectorAll('[type="radio"][name="code"]')
  ].map(node => node.value)
);

console.log(
  $('[type="radio"][name="code"]')
    .map(function () { return this.value; })
    .get()
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="radio" name="code" value="111" />
<input type="radio" name="code" value="222" />
<input type="radio" name="code" value="333" />

【讨论】:

    猜你喜欢
    • 2019-12-05
    • 2013-10-28
    • 2018-02-12
    • 1970-01-01
    • 2021-08-25
    • 2011-07-03
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    相关资源
    最近更新 更多