用jQuery将javascript id放在div中

时间:2009-02-08 04:09:11

标签: javascript jquery

$('div.box').html("hello")

将单词hello放在我所有div类'box'中。他们都有一个指定的身份。

我正在试图弄清楚如何在div中放入每个div的id而不是'hello'。也许这真的很容易,但我无法弄清楚。我也是jQuery的新手。有任何想法吗?我试过了:

$("div.box").html("id: " + $(this).attr("id"));

2 个答案:

答案 0 :(得分:8)

试试这个:

$("div.box").each(function() {
  $(this).html("Id: " + this.id);
});

完整示例:

<html>
<head>
  <title>Layout</title>
</head>
<body>
  <div id="id1" class="box">Box One</div>
  <div id="id2" class="box">Box Two</div>
  <div id="id3">Box Three</div>
  <div id="id4" class="box">Box Four</div>
<script src="http://www.google.com/jsapi"></script>
<script>
  google.load("jquery", "1.3.1");
  google.setOnLoadCallback(function() {
    $(function() {
      $("div.box").each(function() {
        $(this).html("ID: " + this.id);
      });
    });
  });
</script>
</body>
</html>

答案 1 :(得分:5)

您需要遍历每个项目。

$("div.box").each(function()
{
  $(this).html("id: " + this.id);
});