【问题标题】:Several Elements with same Classes . but i can get only first one , why?具有相同类的几个元素。但我只能得到第一个,为什么?
【发布时间】:2020-08-30 10:05:33
【问题描述】:

我有几个具有相同类名的表, 这些表是通过循环从 php 代码创建的。 像这样

<?php 
$tableCount = 100;
$i=rand(1,999);
for ($i = 1; $i <= $tableCount; $i++) {
echo "<table class='tables'>";
echo "<tr class='myTr'>";
echo "<td  class='myTD'>";
echo $i;
echo "</td>";
echo "</tr>";
echo "</table>";
}

所以我们有 100 个不同内容的 td, 我的问题在这里: 当循环在 page 上创建时。当我想获取所有 Td 类的所有 innerHtml 或 html() 编译器给我带来了 td 的第一个 html() 。

我的 jquery 代码:

var getclass = $(".myTD").html();

当我想更改内容或删除或其他东西时;我可以做这个。 例如 : 用于更改具有相同类的所有 td 的所有内容:

 $(".myTD").html("changed contents");

但我想列出。所有 td 的所有 html() 具有相同的类 我的输出应该是这样的:

lists  outputs


  1,     14
  2,     188
  3,     20
  4,     2
  5,     99
  6,     11
  .,      .
  .,      .
  100,    73

并结束。 但 。我的输入让我得到了第一个内容;

我该如何解决。请:(

请注意,我想使用 jquery 或 javascript 来执行此操作。没有 php 或服务器端。

【问题讨论】:

标签: html jquery list class innerhtml


【解决方案1】:

使用.each() 循环。

$(".myTD").each(function(i) {
    console.log(i, $(this).html());
});

【讨论】:

  • 感谢您的回复朋友,我认为这是真的。但是我怎样才能在新的 div 中列出它而不是 console.log 呢?
  • 你可以在函数体中做任何你想做的事情。喜欢$("#newdiv").append(...)
  • 我有意见。我想:当 $("#input").val() == $("#input").each(function() { $(this).html(); });已建立 val 风格的 td 将发生变化。但它不起作用。当我尝试使用这个时: $("#input").val() == $(".myTD").html() ,它给我带来了 td 的第一个值,
  • var x = $("#input").val(); $(".myTD").each(function() { if ($(this).html == x) { do something }})
猜你喜欢
  • 2011-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
  • 2020-10-22
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多