【问题标题】:How to target a table based on ID, in order to iterate through its td-spans, and change spans color aswell as give out its value to console如何根据 ID 定位表,以便遍历其 td-span,并更改跨度颜色以及将其值提供给控制台
【发布时间】:2019-06-07 10:49:54
【问题描述】:

我想用 JQuery 来定位一个表 id,并遍历这个特定的表 td-span,以便将跨度颜色更改为红色并将其值提供给控制台。

我尝试了以下代码,但是样式属性不起作用,console.log()也不起作用

$("span").each(function(index){
this.style.color="red"
console.log(this.innerHTML);
}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Jquery</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  </head>
  <body>
    <table id="IDTable">
      <tr>
        <td>
          <span>Hallo Welt</span>
        </td>
      </tr>
      <tr>
        <td>
          <span>Hallo1</span>
        </td>
      </tr>
      <tr>
        <td>
          <span>Hallo3</span>
        </td>
      </tr>
    </table>
  </body>
</html>

【问题讨论】:

  • 我还想根据 IDS 定位这个特定的表跨度

标签: javascript jquery html css


【解决方案1】:

您的代码缺少结束 );

试试下面的。

$("#IDTable span").each(function(index){
 this.style.color="red"
 console.log(this.innerHTML);
});

不同的是最后一行,我关闭了each 函数。

【讨论】:

  • 谢谢,我怎样才能根据 ID 定位这个特定的表?
  • @Roman 检查我的更新。可以在 jquery 选择器中指定多个标签
【解决方案2】:

这样试试

$("#IDTable tr td span")

$("#IDTable tr td span").each(function(index){
 this.style.color="red";
 console.log(this.innerHTML);
});
<!doctype html>
<html lang="en">
<head>
   <meta charset="utf-8">
  <title>Jquery</title>

  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>


<table id="IDTable">
  <tr>
    <td>
      <span>Hallo Welt</span>
    </td>
  </tr>

  <tr>
    <td>
      <span>Hallo1</span>
    </td>
  </tr>

  <tr>
    <td>
      <span>Hallo3</span>
    </td>
  </tr>



</table>




</body>
</html>

【讨论】:

    【解决方案3】:

    $("#IDTable td span").each(function(index){
       this.style.color="red"
       console.log(this.innerHTML);
    });
    <!doctype html>
    <html lang="en">
    <head>
       <meta charset="utf-8">
      <title>Jquery</title>
      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    </head>
    <body>
    
    
    <table id="IDTable">
      <tr>
        <td>
          <span>Hallo Welt</span>
        </td>
      </tr>
      <tr>
        <td>
          <span>Hallo1</span>
        </td>
      </tr>
      <tr>
        <td>
          <span>Hallo3</span>
        </td>
      </tr>
    </table>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2015-07-21
      • 1970-01-01
      • 2022-01-12
      • 2021-12-18
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多