2018-10-10 22:03:03 +00:00
|
|
|
---
|
|
|
|
id: 587d7fa6367417b2b2512bc3
|
2021-03-09 15:51:59 +00:00
|
|
|
title: 用 D3 选择一组元素
|
2018-10-10 22:03:03 +00:00
|
|
|
challengeType: 6
|
2020-09-17 16:13:05 +00:00
|
|
|
forumTopicId: 301490
|
2021-01-13 02:31:00 +00:00
|
|
|
dashedName: select-a-group-of-elements-with-d3
|
2018-10-10 22:03:03 +00:00
|
|
|
---
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --description--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-09 15:51:59 +00:00
|
|
|
`selectAll()` 方法选择一组元素。 它以 HTML 节点数组的形式返回该文本中所有匹配所输入字符串的对象。 以下是一个选择文本中所有锚标签的例子:
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
`const anchors = d3.selectAll("a");`
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-09 15:51:59 +00:00
|
|
|
像 `select()` 方法一样,`selectAll()` 也支持链式调用,你可以在它之后调用其他方法。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --instructions--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-09 15:51:59 +00:00
|
|
|
选择所有的 `li` 标签,通过 `.text()` 方法将它们的文本改为 `list item`。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --hints--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-09 15:51:59 +00:00
|
|
|
页面上应该有 3 个 `li` 元素,每个元素的文本内容应为 `list item`。 大小写和空格必须一致。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
```js
|
|
|
|
assert(
|
|
|
|
$('li')
|
|
|
|
.text()
|
|
|
|
.match(/list item/g).length == 3
|
|
|
|
);
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
|
|
|
|
2021-03-09 15:51:59 +00:00
|
|
|
应该能访问 `d3` 的对象。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
```js
|
|
|
|
assert(code.match(/d3/g));
|
|
|
|
```
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-09 15:51:59 +00:00
|
|
|
应该使用 `selectAll` 方法。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
```js
|
|
|
|
assert(code.match(/\.selectAll/g));
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
2020-08-13 15:24:35 +00:00
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
```html
|
|
|
|
<body>
|
|
|
|
<ul>
|
|
|
|
<li>Example</li>
|
|
|
|
<li>Example</li>
|
|
|
|
<li>Example</li>
|
|
|
|
</ul>
|
|
|
|
<script>
|
|
|
|
// Add your code below this line
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Add your code above this line
|
|
|
|
</script>
|
|
|
|
</body>
|
|
|
|
```
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --solutions--
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
```html
|
|
|
|
<body>
|
|
|
|
<ul>
|
|
|
|
<li>Example</li>
|
|
|
|
<li>Example</li>
|
|
|
|
<li>Example</li>
|
|
|
|
</ul>
|
|
|
|
<script>
|
|
|
|
d3.selectAll("li")
|
|
|
|
.text("list item")
|
|
|
|
</script>
|
|
|
|
</body>
|
|
|
|
```
|