2009-02-08 60 views
2
$('div.box').html("hello") 

在单词'box'的所有div中放入hello这个词。他们都有一个分配的ID。将jQuery中的javascript id放入div中

我想弄清楚如何把每个div的id而不是'你好'的div内。也许这很容易,但我无法弄清楚。我也是jQuery的新手。有任何想法吗?我已经试过:

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

那么这就是weirde ......接受然后不被接受。流年。 :) – cletus 2009-02-08 12:24:59

回答

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> 
+0

完美。谢谢。 – bbarnhart 2009-02-08 12:17:36

5

你要通过每个项循环。

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