CSS 定義 path[data-classbreak="classbreak0"] { fill: #00008B; },需用 jQuery 動態修改該選擇器下的 fill 屬性。
// 錯誤:path 是標簽選擇器,但這裡 path 是 SVG 元素,且類名寫法錯誤
$("path[data-classbreak='classbreak0']").css("fill", "#33FF00");
// SVG path 元素帶 data-classbreak 屬性
$("path[data-classbreak='classbreak0']").css("fill", "#33FF00");
// 若 path 同時有 class="path"
$(".path[data-classbreak='classbreak0']").css("fill", "#33FF00");
path 選 SVG <path> 標簽;.path 選 class="path"。原問題中 node.setAttribute("data-classbreak", "classbreak0") 操作的是 SVG <path> 元素,故用標簽選擇器 path。[attr="value"] 精確匹配;[attr^="val"] 前綴;[attr$="val"] 後綴;[attr*="val"] 包含。.css("fill", "#33FF00") 會在元素 style 屬性中添加 fill: #33FF00,優先級高於外部 CSS,立即生效。
<svg width="200" height="200">
<path id="p1" data-classbreak="classbreak0" d="M10 10 L100 100" stroke="black" fill="#00008B" />
<path id="p2" data-classbreak="classbreak1" d="M10 100 L100 10" stroke="black" fill="#1E90FF" />
</svg>
<button id="btnChange">修改 classbreak0 fill</button>
<script>
$('#btnChange').click(function() {
// 正確選擇並修改
$("path[data-classbreak='classbreak0']").css("fill", "#33FF00");
console.log("已修改 fill 為 #33FF00");
});
</script>
$("path[data-classbreak]").each(function() {
var cls = $(this).data("classbreak");
var newFill = {
"classbreak0": "#FF0000",
"classbreak1": "#00FF00",
"classbreak2": "#0000FF"
}[cls];
if (newFill) $(this).css("fill", newFill);
});
掌握 標簽選擇器 + [屬性選擇器] 組合,即可精準定位並動態修改 SVG/HTML 元素基於 data-* 屬性的 CSS 樣式。