3.4 KiB
3.4 KiB
id | title | required | challengeType | videoUrl | localeTitle | |||
---|---|---|---|---|---|---|---|---|
587d7fa7367417b2b2512bc4 | Work with Data in D3 |
|
6 | 在D3中使用数据 |
Description
data()
方法用于选择DOM元素以将数据附加到这些元素。数据集作为参数传递给方法。常见的工作流模式是在文档中为集合中的每个数据创建一个新元素。 D3为此目的使用了enter()
方法。当enter()
与data()
方法结合使用时,它会查看页面中的选定元素,并将它们与集合中的数据项数量进行比较。如果元素少于数据项,则会创建缺少的元素。下面是一个示例,它选择一个ul
元素并根据数组中的条目数创建一个新的列表项: <BODY>选择尚不存在的元素似乎令人困惑。此代码告诉D3首先选择页面上的
<UL> </ UL>
<SCRIPT>
const dataset = [“a”,“b”,“c”];
d3.select( “UL”)。全选( “礼”)
。数据(数据集)
。输入()
.append( “里”)
.text(“新项目”);
</ SCRIPT>
</ BODY>
ul
。接下来,选择所有列表项,返回空选择。然后data()
方法检查数据集并运行以下代码三次,对于数组中的每个项目运行一次。 enter()
方法看到页面上没有li
元素,但它需要3(数据dataset
每个数据对应一个)。新的li
元素被附加到ul
并具有文本“New item”。 Instructions
body
节点,然后选择所有h2
元素。让D3为dataset
数组中的每个项创建并附加h2
标记。 h2
的文字应该说“新标题”。您的代码应使用data()
和enter()
方法。 Tests
tests:
- text: 您的文档应该有9个<code>h2</code>元素。
testString: 'assert($("h2").length == 9, "Your document should have 9 <code>h2</code> elements.");'
- text: <code>h2</code>元素中的文本应该是“New Title”。大写和间距应完全匹配。
testString: 'assert($("h2").text().match(/New Title/g).length == 9, "The text in the <code>h2</code> elements should say "New Title". The capitalization and spacing should match exactly.");'
- text: 您的代码应该使用<code>data()</code>方法。
testString: 'assert(code.match(/\.data/g), "Your code should use the <code>data()</code> method.");'
- text: 您的代码应使用<code>enter()</code>方法。
testString: 'assert(code.match(/\.enter/g), "Your code should use the <code>enter()</code> method.");'
Challenge Seed
<body>
<script>
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
// Add your code below this line
// Add your code above this line
</script>
</body>
Solution
// solution required