


Detailed explanation of data(), enter() and exit() problems in D3.js_javascript skills
D3 is widely used and has now become one of the mainstream data visualization tools. When everyone first came into contact with d3.js, the most difficult parts were the operations of data(), enter(), and exit().
After I have been in contact with it for a period of time and gained some understanding, I would like to briefly talk about my understanding.
data()
Let’s look at an example first:
<body> <p></p> <p></p> <p></p> </body>
Execution code:
d3.select("body").selectAll("p").data([1, 2, 3])
Here, data() is used to bind data to the selected DOM element. In this way, you can do some related operations on the data, such as setting the element width, etc.
On the surface, no changes can be seen. But internally, it adds a __data__ attribute to the corresponding DOM element, which can be seen through document.getElementsByTagName("p")[0].__data__.
enter() and exit()
These two operations are confusing because it is difficult to deduce what they do from their names alone.
In the above example of data(), the number of our DOM elements and data are the same. But if it's different, what should we do?
enter() and exit() are used to handle this situation.
enter()
When the number of DOM is less than the number of data, or there is none at all, we usually want to let the program help create it.
In the following example, we do not provide DOM elements in advance:
<body> </body>
Still executed:
d3.select("body").selectAll("p").data([1, 2, 3])
The difference from the above example is that in the above example we can continue to perform operations such as .style("width", "100px"). But we can't do that here, because we haven't selected the DOM element and need to create it first.
enter() is used to select the missing part of DOM elements after binding data. We may wonder, since it is the missing part, how to choose? Here we need to use a little imagination and imagine that we have chosen something that does not exist. We can call it "virtual DOM" or "placeholder".
enter() only makes a selection and does not actually add the required DOM elements. Therefore, after enter(), append() is usually used to actually create the DOM element.
From now on, we use d3.select("body").selectAll("p").data([1, 2, 3]).enter().append("p") to Automatically create the required DOM elements.
How to handle enter
If there are not enough elements, the usual approach is to add elements using append(). Please look at the code below:
<body> <p></p> <script> var dataset = [3, 6, 9]; var p = d3.select("body").selectAll("p"); //绑定数据后,分别获取update和enter部分 var update = p.data(dataset); var enter = update.enter(); //update部分的处理方法是直接修改内容 update.text( function(d){ return d; } ); //enter部分的处理方法是添加元素后再修改内容 enter.append("p") .text(function(d){ return d; }); </script> </body>
In this example, there is only one p element in the body, but there are three data, so the enter part contains two extra data. The method to deal with redundant data is the append element, which corresponds to it. After processing, there are three p elements in the body, the contents of which are:
<p>3</p> <p>6</p> <p>9</p>
Usually, after reading the file from the server, the data is there, but there are no elements in the web page. This is a very important feature of D3, that is, you can select an empty set and then use enter().append() to insert elements. Assuming there is no p element in the body now, please see the following code:
var dataset = [10,20,30,40,50]; var body = d3.select("body"); body.selectAll("p") //选择body中所有p,但由于没有p,所以选择了一个空集 .data(dataset) //绑定dataset数组 .enter() //返回enter部分 .append("p") //添加p元素 .text(function(d){ return d; });
In the above code, selectAll selects an empty set and then binds the data. Since the selection set is empty, the update part returned by data() is empty. Then call enter() and append() so that each data has an element p corresponding to it. Finally, change the content of the p element. That is, the common way to deal with the enter part is to use append() to add elements.
exit()
Contrary to enter(), exit() is used to select those DOM elements that are extra compared to the data.
In the following example, we provide one more DOM element:
<body> <p></p> <p></p> <p></p> <p></p> </body>
This time it is easy to understand, because it is extra, then it actually exists, that is, the last
.
If there are more, we can then use .remove() to remove these elements. The code is as follows:
d3.select("body").selectAll("p").data([1, 2, 3]).exit().remove();
How to handle exit
There are too many elements and no data corresponding to them. For such elements, the usual approach is to use remove() to delete the element. Assuming there are 5 p elements in the body, please see the following code:
var dataset = [10, 20, 30]; var p = d3.select("body").selectAll("p"); //绑定数据之后,分别获取update部分和exit部分 var update = p.data(dataset); var exit = update.exit(); //update的部分的处理方法是修改内容 update.text( function(d){ return d; } ); //exit部分的处理方法是删除 exit.remove();
In this code, the exit part is processed by deletion. After deletion, there will be no redundant p elements in the web page.
Reference materials

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
