$("#btn_addName_grade").click(function(){
var i = 2015;
$("li").each(function(j){
$("legend").html(i - j + "級"); // 錯誤:每次迴圈都選中所有 legend
});
});
$("legend") 是全局選擇器,每次迴圈都會選中頁面**所有** <legend> 元素並設置相同內容,最終所有年級組顯示同一值(最後一次迴圈的值)。
$("#btn_addName_grade").click(function(){
var i = 2015;
$("li").each(function(j){
// 使用 this 指向當前 li,配合 find/context 限定範圍
$("legend", this).html(i - j + "級");
// 或 $(this).find("legend").html(...)
});
});
each(callback) 中 this 指向當前迴圈的 DOM 元素。context:$("selector", context) 等價 $(context).find("selector")。<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
$(function(){
$("#btn_add_grade").click(function(){
$("ul").append('<li><fieldset><legend>未命名年級組</legend><text>1班</text></fieldset></li>');
});
$("#btn_addName_grade").click(function(){
var baseYear = 2015;
$("li").each(function(idx){
$(this).find("legend").html(baseYear - idx + "級");
});
});
});
</script>
</head>
<body>
<button id="btn_add_grade">添加年級組</button>
<button id="btn_addName_grade">年級組自動命名</button>
<ul></ul>
</body>
</html>