找到行后,我试图突出显示一些td元素。
我设法在两个不同的步骤中找到了row和td元素(注释为“ Works OK”)。我想在一个for循环中合并这两个步骤,但是它不起作用。



$(document).ready(function() {
  var dt = ['2017-11-02', '2017-11-03'];
  cell = $('td:contains("value1")');

  // works OK
  $(cell).css({
    color: "red",
    border: "2px solid red"
  });

  for (var i = 0; i < dt.length; i++) {
    // works OK
    $('[data-date="' + dt[i] + '"]').css({
      background: "blue",
      color: "white"
    });

    // Not Working
    //$('td:contains("value1")').find('[data-date="' + dt[i] + '"]').css({background:"blue", color:"white"});
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
  <table>
    <tr>
      <td>text1</td>
      <td>value1</td>
      <td data-date="2017-11-01">1</td>
      <td data-date="2017-11-02">2</td>
      <td data-date="2017-11-03">3</td>
      <td data-date="2017-11-04">4</td>
    </tr>
    <tr>
      <td>text2</td>
      <td>value2</td>
      <td data-date="2017-11-01">1</td>
      <td data-date="2017-11-02">2</td>
      <td data-date="2017-11-03">3</td>
      <td data-date="2017-11-04">4</td>
    </tr>
</div>





问候,
埃里奥·费尔南德斯(Elio Fernandes)

最佳答案

你可以更换

$('[data-date="' + dt[i] + '"]').css({




$(cell).parent().children('[data-date="' + dt[i] + '"]').css({


您可以用find替换子级,并用另一种方式替换$(cell).parent()来专注于tr。



$(document).ready(function() {
  var dt = ['2017-11-02', '2017-11-03'];
  cell = $('td:contains("value1")');

  // works OK
  $(cell).css({
    color: "red",
    border: "2px solid red"
  });

  for (var i = 0; i < dt.length; i++) {
    // works OK
    $(cell).parent().children('[data-date="' + dt[i] + '"]').css({
      background: "blue",
      color: "white"
    });
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
  <table>
    <tr>
      <td>text1</td>
      <td>value1</td>
      <td data-date="2017-11-01">1</td>
      <td data-date="2017-11-02">2</td>
      <td data-date="2017-11-03">3</td>
      <td data-date="2017-11-04">4</td>
    </tr>
    <tr>
      <td>text2</td>
      <td>value2</td>
      <td data-date="2017-11-01">1</td>
      <td data-date="2017-11-02">2</td>
      <td data-date="2017-11-03">3</td>
      <td data-date="2017-11-04">4</td>
    </tr>
</div>

09-18 13:11