用jQuery将javascript id放在div中

bba*_*art 2 javascript jquery

$('div.box').html("hello")
Run Code Online (Sandbox Code Playgroud)

在我的所有div'类'box'中加入hello这个词.他们都有一个指定的身份证.

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

$("div.box").html("id: " + $(this).attr("id"));
Run Code Online (Sandbox Code Playgroud)

cle*_*tus 8

试试这个:

$("div.box").each(function() {
  $(this).html("Id: " + this.id);
});
Run Code Online (Sandbox Code Playgroud)

完整示例:

<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>
Run Code Online (Sandbox Code Playgroud)


ben*_*wey 5

你想要遍历每个项目.

$("div.box").each(function()
{
  $(this).html("id: " + this.id);
});
Run Code Online (Sandbox Code Playgroud)