简体   繁体   English

这个例子中的.html() d3.js 方法 function 是怎么做的?

[英]How does the .html() d3.js method function in this example?

post edited with complete code:使用完整代码编辑的帖子:

this is my first post so please tell me if I'm wrong in any way.这是我的第一篇文章,所以如果我有任何错误,请告诉我。

I'm a university student (communication) and I'm triyng to do a little project to pass an exam.我是一名大学生(交流),我正在尝试做一个小项目以通过考试。

My goal is to make a time table for Radio programs with javascript and D3.我的目标是为带有 javascript 和 D3 的广播节目制作时间表。 I know there are best way... but these are the topic of the course, so I have to use them.我知道有最好的方法......但这些是课程的主题,所以我必须使用它们。

I had a big help from a friend of mine who has given me this suggestion to put a link inside every <td> of the table:我的一个朋友给了我很大的帮助,他给了我这个建议,在表格的每个<td>中放置一个链接:

Here it is the complete HTML code:这是完整的 HTML 代码:

<!DOCTYPE html>
<html lang = "it">
    <head>
        <title>Palinsesto</title>
        <meta charset="utf-8">
        <link rel="icon" href="CoronaVirus.png" sizes= "130x130">
        <link rel="stylesheet" href="stilePalinsesto.css" media="all">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script>
        <script src="TabellaPalinsesto.js" defer></script>
    </head>
    <body><!-- il body è costruito in javascript --> </body>
</html>

and this is TabellaPalinsesto.js这是 TabellaPalinsesto.js

 /* inserimento titolo h2 e paragrafo */
d3.select("body")
    .append("h2")
    .text("Palinsesto programmi 2021")
d3.select("body")
    .append("p")
    .text("Qui trovate la nostra programmazione settimanale: cliccate sul nome del proogramma per aprire la pagina relativa")

/* inserimento dell'intestazion della tabella con le relative etichette */
d3.select("body")
    .append("table")
    .append("thead")
    .append("tr")
    .selectAll("th")
    .data(["dalle", "alle", "LUNEDI", "MARTEDI", "MERCOLEDI", "GIOVEDI",
        "VENERDI", "SABATO", "DOMENICA"
    ])
    .enter()
    .append("th")
    .text(function (d) { return d });

d3.select("table")
    .append("tbody")
    .enter();

/*divisione di ogni dato array in 3 parti ProgrammaNome, ProgrammaUrl e datoClasse */
d3.csv("Palinsesto.csv", function (datiCaricati) {
    console.log(datiCaricati);
    var d = datiCaricati;
    d3.select("tbody")
        .append("tr")
        .selectAll("td")
        .data([d.dalle, d.alle, d.LUNEDI, d.MARTEDI, d.MERCOLEDI, d.GIOVEDI, d.VENERDI, d.SABATO, d.DOMENICA])
        .enter()
        .append("td")
        .html(function (cella) {
                const [ProgrammaNome, ProgrammaUrl, classeCella] = cella.split("|");
                /* se la cella ha il valore dell'url, inserisco un link */
                if (ProgrammaUrl) {
                   return "<a href='" + ProgrammaUrl + "' target='blank' \">" + ProgrammaNome + "</a>"
                }
                /* altrimenti mostro un testo normale */
                /*Se non ci fosse le colonne "dalle" e "alle" non verrebbero visualizzate */
                else {
                    return ProgrammaNome
                }
              }
             )
    
});

I dont understand very well:我不是很明白:

.html(function (cella)

How.html method works in javascript? html 方法如何在 javascript 中工作? Where can I find any docs?我在哪里可以找到任何文档?

The question is related to the use of d3.js, which indeed has a.html() method as @AndrewReid correctly stated (and linked to the docs ).该问题与 d3.js 的使用有关,它确实具有 @AndrewReid 正确说明的 a.html() 方法(并链接到文档)。 It is similar to the.text() method, which sets the.innerText property of element(s), but it sets the.innerHTML property of the element(s) in the current selection.它类似于 .text() 方法,它设置元素的 .innerText 属性,但它设置当前选择中元素的 .innerHTML 属性。

What the.html() method does is the following: .html() 方法的作用如下:

  • If it is passed a value, it simply sets the innerHTML of the element(s) to that value如果它被传递了一个值,它只是将元素的 innerHTML 设置为该值
  • If it is passed a function (as in your example), it evaluates the function and sets the innerHTML of the element(s) to the function return value.如果传递了 function (如您的示例中所示),它将评估 function 并将元素的 innerHTML 设置为 ZC1C425268E68385D1AB5074C17A94F14 返回值。
    • The function is fed the arguments: (d, i, nodes), where d is the current datum and i is the current index, and nodes is the current selection. function 被馈送到 arguments:(d, i, nodes),其中 d 是当前基准,i 是当前索引,nodes 是当前选择。

Let's start with a simple example (see code snippet below):让我们从一个简单的例子开始(见下面的代码片段):

  • I defined some example data ( myData ), which I think might closely resemble what yours looks like based on the code.我定义了一些示例数据( myData ),我认为这些数据可能与您基于代码的外观非常相似。
  • Ignore the "thead" "tr" and "th" creation, for now, the section after // create the table header:忽略 "thead" "tr" 和 "th" 创建,现在, // create the table header:
  • Focus on the "tbody" "tr" and "td" creation, for now, the section after // create the table body:专注于 "tbody" "tr" 和 "td" 创建,现在, // create the table body:
  • (The "outer loop") We select all "tr" (and none exist), so the selection is empty, but then we bind myData to this selection, and then .enter() this selection. (“外循环”)我们 select 都是“tr”(并且不存在),所以选择是空的,但是我们将myData绑定到这个选择,然后.enter()这个选择。 This essentially means, we enter a selection equal to the length of our data, and at each item in our data, we can do something - ie we can .append("tr") .这实质上意味着,我们输入一个等于我们数据长度的选择,并且在我们数据中的每个项目上,我们可以做一些事情 - 即我们可以.append("tr") This means we will create N new "tr" elements, where N is equal to myData.length .这意味着我们将创建 N 个新的“tr”元素,其中 N 等于myData.length
  • (The "inner loop") Then we repeat this process but one level deeper, by binding the empty "td" selection to a new array of data, equal to the current values of the outer loop's iteration. (“内循环”)然后我们重复这个过程,但更深一层,将空的“td”选择绑定到一个新的数据数组,等于外循环迭代的当前值。 We wrote it manually here, but we could have written .data(d => Object.values(d)) .我们在这里手动编写,但我们可以编写.data(d => Object.values(d))
  • We then .enter() this inner loop's iteration, and we create M new "td" elements, where M is equal to Object.values(myData[i]) , where i is the current index of the outer loop.然后我们.enter()这个内部循环的迭代,我们创建 M 个新的“td”元素,其中 M 等于Object.values(myData[i]) ,其中i是外部循环的当前索引。
  • Therefore, we can summarize by saying, that we iterate over the rows of our data and create the corresponding "tr" elements, and then within each row, we iterate of the columns of our data and create the corresponding "td" elements.因此,我们可以总结为,我们迭代数据的行并创建相应的“tr”元素,然后在每一行中,我们迭代数据的列并创建相应的“td”元素。 However, these "td" elements are empty at this point, and this is where.html() comes in:但是,此时这些“td”元素是空的,这就是 .html() 的用武之地:
  • We can pass a function to.html() as stated earlier, and the d argument that is passed in, is equal to the current data item of the iteration, that was bound with .data(...) .如前所述,我们可以将 function 传递给 .html() ,传入的d参数等于迭代的当前数据项,它与.data(...)绑定。 So in our case, this means firstly 'mon1|www.mon1.com|some-class' , then 'tue1|www.tue1.com|some-class' , and then 'wed1|www.wed1.com|some-class' and then we have finished our first inner loop and we progress with the next iteration of the outer loop (and its inner loop).所以在我们的例子中,这意味着首先是'mon1|www.mon1.com|some-class' ,然后'tue1|www.tue1.com|some-class' ,然后'wed1|www.wed1.com|some-class'然后我们完成了我们的第一个内部循环,我们继续进行外部循环(及其内部循环)的下一次迭代。
  • The function that we passed into.html() then simply splits the string on the "|"我们传入 .html() 的 function 然后简单地拆分"|"上的字符串character and proceeds to construct an anchor tag "a" with the corresponding class, href, and innerText.字符并继续使用相应的 class、href 和 innerText 构造一个锚标记“a”。

 const myData = [ {mon: 'mon1|www.mon1.com|some-class', tue: 'tue1|www.tue1.com|some-class', wed: 'wed1|www.wed1.com|some-class'}, {mon: 'mon2|www.mon2.com|some-class', tue: 'tue2|www.tue2.com|some-class', wed: 'wed2|www.wed2.com|some-class'} ] // create the table header: d3.select("table").append("thead").append("tr").selectAll("th").data(Object.keys(myData[0])).enter().append("th").text(d => d); // create the table body: d3.select("table").append("tbody").selectAll("tr").data(myData).enter().append("tr").selectAll("td").data(d => [d.mon, d.tue, d.wed]) // Object.values(d).enter().append("td").html(function(d) { const [ProgrammaNome, ProgrammaUrl, classeCella] = d.split("|"); return `<a class="${classeCella}" href="${ProgrammaUrl}" target="blank">${ProgrammaNome}</a>`; } )
 table, table td, table th { border: solid 1px black; border-collapse: collapse; } table td, table th { padding: 5px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <table></table>

Note, you technically don't need to use.html() for this example, you could do it like this:请注意,从技术上讲,此示例不需要 use.html(),您可以这样做:

 const myData = [ {mon: 'mon1|www.mon1.com|some-class', tue: 'tue1|www.tue1.com|some-class', wed: 'wed1|www.wed1.com|some-class'}, {mon: 'mon2|www.mon2.com|some-class', tue: 'tue2|www.tue2.com|some-class', wed: 'wed2|www.wed2.com|some-class'} ] // create the table header: d3.select("table").append("thead").append("tr").selectAll("th").data(Object.keys(myData[0])).enter().append("th").text(d => d); // create the table body: d3.select("table").append("tbody").selectAll("tr").data(myData).enter().append("tr").selectAll("td").data(d => [d.mon, d.tue, d.wed]).enter().append("td").append("a").attr("class", d => d.split("|")[2]).attr("href", d => d.split("|")[1]).text(d => d.split("|")[0]);
 table, table td, table th { border: solid 1px black; border-collapse: collapse; } table td, table th { padding: 5px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <table></table>

If you want to visualize the inner and outer loops, maybe this example will help.如果您想可视化内部和外部循环,也许这个例子会有所帮助。 (i, j) = (row, col): (i, j) = (行, 列):

在此处输入图像描述

 const myData = [ {mon: 'mon1|www.mon1.com|some-class', tue: 'tue1|www.tue1.com|some-class', wed: 'wed1|www.wed1.com|some-class'}, {mon: 'mon2|www.mon2.com|some-class', tue: 'tue2|www.tue2.com|some-class', wed: 'wed2|www.wed2.com|some-class'} ] // create the table header: d3.select("table").append("thead").append("tr").selectAll("th").data(Object.keys(myData[0])).enter().append("th").text(d => d); // create the table body: d3.select("table").append("tbody").selectAll("tr").data(myData).enter().append("tr").selectAll("td").data((d,i) => [i, i, i]).enter().append("td").text((i,j) => `${i},${j}`);
 table, table td, table th { border: solid 1px black; border-collapse: collapse; } table td, table th { padding: 5px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <table></table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM