【问题标题】:Creating array from html to display using D3 Wordcloud使用 D3 Wordcloud 从 html 创建数组以显示
【发布时间】:2015-01-26 10:15:45
【问题描述】:

恐怕这是一个关于从 HTML 元素构建数组的非常基本的 Javascript 问题。我一直在寻找答案,但我认为有一些重要的基础知识对我来说没有用,而且我正在兜圈子,所以一些外部专家的观点将不胜感激!

我们正在使用 Moodle 运行在线课程,在介绍周,我们希望通过数据库模块(例如国家/地区)收集有关用户的一些信息,然后向他们展示小组响应。

Moodle 提供一个带有占位符 [[data]] 的模板,您可以将其包装在 html 中,在本例中为 div:

 <div class="country">[[country]]</div>

我遇到的问题是将所有这些 div 的内容放入一个数组中。我发现这里解释了这个方法,但我的 push/concat 尝试似乎不起作用:

var countryList = document.getElementsByClassName("country");    
Array.prototype.forEach.call(countryList, function() {}); 

我希望它在一个数组中的原因是我可以使用 Jason Davies 的 d3.js 驱动的词云将内容推送到现有模板中。 Here's a link to GitHub,下面复制一个简单云的非常基本的代码以供参考。

基本上我希望能够从 HTML 元素中创建一个数组,并将其与下面使用的单词数组结合起来:

var fill = d3.scale.category20();

d3.layout.cloud().size([300, 300])
  .words([
    "Hello", "world", "normally", "you", "want", "more", "words",
    "than", "this"
  ].map(function(d) {
    return {
      text: d,
      size: 10 + Math.random() * 90
    };
  }))
  .padding(5)
  .rotate(function() {
    return ~~(Math.random() * 2) * 90;
  })
  .font("Impact")
  .fontSize(function(d) {
    return d.size;
  })
  .on("end", draw)
  .start();

function draw(words) {
  d3.select("body").append("svg")
    .attr("width", 300)
    .attr("height", 300)
    .append("g")
    .attr("transform", "translate(150,150)")
    .selectAll("text")
    .data(words)
    .enter().append("text")
    .style("font-size", function(d) {
      return d.size + "px";
    })
    .style("font-family", "Impact")
    .style("fill", function(d, i) {
      return fill(i);
    })
    .attr("text-anchor", "middle")
    .attr("transform", function(d) {
      return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
    })
    .text(function(d) {
      return d.text;
    });
}

【问题讨论】:

    标签: javascript arrays d3.js moodle word-cloud


    【解决方案1】:

    您应该能够使用以下方式获取所需的数组:

    var countryList = document.querySelectorAll('.country');   
    var countryNames = Array.prototype.map.call(countryList, function(c){return c.textContent}); 
    

    【讨论】:

    • 请记住,document.getElementsByClassName() 的支持较少(感谢 IE 8)比 document.querySelectorAll()
    • @DavidThomas 那是指使用document.querySelectorAll("*.country") 代替,对吧?
    • 或者只是document.querySelectorAll('.country'),或者document.querySelectorAll('div.country'),但基本上:是的,它使用CSS选择器语法。
    • 太好了,工作! (也感谢有关 document.getElementByClassName 的提示)。
    猜你喜欢
    • 2015-04-08
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 2021-02-21
    • 2017-08-25
    • 2015-10-08
    相关资源
    最近更新 更多