0

我正在尝试用 svg 制作一个交互式图表,其中包含边缘的路径和节点的圆。为了找到一个节点的子节点,我希望能够使用某个正则表达式搜索边缘的 id,因为这些 id 都是以下形式:“node1_id node2_id”。我尝试了许多解决方案,包括美元美元符号和将正则表达式直接放入 id 的查找元素中,但我没有运气。我找不到其他可以回答这个问题的东西,而且我对前端交易很陌生,所以我不确定这是否是 svg 特有的东西。

$$('path[id^="\b10020 ([\d]+)"')
Error: SYNTAX_ERR: DOM Exception 12

document.getElementById("\b10020 ([\d]+)")
null

可能是我做过的两个最明智的尝试。在这种情况下,所有 node1_id 为 10020 的边。

<path fill="none" stroke-width="1.0"
              d="M -1026.321777,958.875610 C -987.123413,912.258789 -858.400574,901.130981 -811.783752,940.329346"
              id="10020 12050" stroke-opacity="1.0" stroke="#7dcb3c"/>

作为一个应该返回匹配的边缘的示例。

4

2 回答 2

1

如果我这样做,我会将标记更改为:

<path fill="none" stroke-width="1.0"
      d="M -1026.321777,958.875610 C -987.123413,912.258789 -858.400574,901.130981 -811.783752,940.329346"
      data-node-1="10020" data-node-2="12050" stroke-opacity="1.0" stroke="#7dcb3c"/>

然后使用“单美元符号”(又名,jQuery):

$('path[data-node-1="10020"]')
于 2012-08-30T17:43:39.130 回答
0

There is no CSS selector that accepts regular expressions, not even in the next level 4 version. [foo^=bar] means "an element whose foo attribute value begins exactly with the string bar". You can do several things:

  • if all you want is nodes with an ID beginning with 10020, then you can use $$("path[id^='10020 ']") but this will accept IDs that don't continue with other digits only
  • if you want the 10020 value to appear in the ID, regardless of the position, then use the path[id~='10020'] selector
  • if you really need to use regular expressions, then you have to walk the tree yourself and filter only the elements that you're interested in; you can optimize a bit by pre-filtering according to one of the selectors above, so that you have to check only the elements that do start with 10020

However, there is one big problem with your usecase: IDs may not contain spaces, that's an invalid SVG document. You really must use another attribute than id, maybe class is better suited for you, or if there is a semantic meaning to those numbers, define your own namespace and use new attributes in that namespace.

If you use class, then your selectors could also become simpler: $$("path.10020")

于 2012-08-30T19:32:38.487 回答