javascript - d3.select 不适用于特殊字符

标签 javascript d3.js

我正在使用 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/

相关文章:

javascript - postman 回复 : Could not get any response from server

javascript - D3 力向图 : update node position

javascript - SVG D3 图像调整大小问题

javascript - 在 d3 中的多轴折线图上添加 x 和 y2 轴的工具提示和焦点引导

php - 以编程方式检查图像元素颜色和颜色百分比

javascript - 如何调整我的 iframe

javascript - Rhino 功能超出 ECMA 标准?

javascript - 如何使用 jQuery 和 JavaScript 获取 URL 的特定部分?

javascript - SVG 路径笔画-破折号数组转换在某些浏览器中向后工作 -d3js

javascript - 在堆叠条形图中使用图例以及工具提示 d3 js