JavaScript:将第一个字符串存储在for循环中的值中吗?

时间:2015-11-12 13:32:59

标签: javascript

var tds = document.getElementsByClassName('ms-cellstyle ms-vb2');
for (var i = 0; i < tds.length; i++) {
    if (tds[i].innerHTML.indexOf('Routed') >= 0 && i < tds.length - 1) {
        console.log(tds[i + 1].innerHTML);
    }
}

我如何存储第一个值? 这个循环拉出了下一个兄弟姐妹W1234567,A5364274,G8367483的列表。 在这种情况下需要存储的第一个值是从列表“W1234567”

Console image

1 个答案:

答案 0 :(得分:0)

检索第一次出现?这是你的意思吗?

如果是这样,请创建一个函数并传入参数。当条件为真时立即返回。

&#13;
&#13;
function getFirst(className, criteria) {
  var tds = document.getElementsByClassName(className);
  for (var i = 0; i < tds.length; i++) {
    if (tds[i].innerHTML.indexOf(criteria) >= 0 && i < tds.length - 1) {
      return tds[i];
    }
  }
  return null;
}

// The target call to highlight.
var targetCell = null;

// The cell with "Routed" in it's text.
var matched = getFirst('ms-cellstyle ms-vb2', 'Routed');

if (matched != null) {
  // Fist sibling is the text of the matched cell, we need the one after that.
  targetCell = matched.nextSibling.nextSibling;
}

if (targetCell != null) {
  targetCell.className += ' found'; // Highlight cell
}
&#13;
table, tr, td {
  border: thin solid #000;
  border-collapse: collapse;
}

.found {
  background: #FF0;
}
&#13;
<table>
  <tr>
    <td class="ms-cellstyle ms-vb2">Not in OMS</td>
    <td class="ms-cellstyle ms-vb2">A5364274</td>
  </tr>
  <tr>
    <td class="ms-cellstyle ms-vb2">Routed: Less Than 24 Hours</td>
    <td class="ms-cellstyle ms-vb2">W1234567</td>
  </tr>
  <tr>
    <td class="ms-cellstyle ms-vb2">Undefined</td>
    <td class="ms-cellstyle ms-vb2">G8367483</td>
  </tr>
</table>
&#13;
&#13;
&#13;

旁注:您可以调整for循环条件以与内部if条件一致。

for (var i = 0; i < tds.length - 1; i++) {