我正在使用 d3.js 制作简单图表。假设在我计划放置我的 d3 svg 容器的 div 之后
<div id="my~div_chart">
但是当我使用
d3.select('#my~div_chart')
我无法选择特定的 div,但是通过使用 java 脚本选择器,它可以工作。
document.getElementById("my~div_chart");
谁能告诉我为什么会这样。如果是特殊字符问题,请告诉我支持哪些特殊字符。
最佳答案
它就在那里,在 specifications 中:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F". (emphasis mine)
除此之外,~
是兄弟组合器:
The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.
因此,如果您仍想使用该 ID,则必须使用 "#my\\~div_chart"
转义波浪号:
d3.select("#my\\~div_chart").on("click", function(){
d3.select(this).style("background-color","teal")
});
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="my~div_chart">Click Me</div>
最后,在您的问题中,您说 document.getElementById
有效。但是,请记住 document.querySelector
会失败。
关于javascript - d3.select 不适用于特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41296586/