如何使用在javascript中创建的对象在html中创建表

How to create a table in html using an object created in javascript?

本文关键字:创建 html 对象 何使用 javascript      更新时间:2023-09-26

我已经开始从事web开发,特别是JavaScript和node.js,并创建了一个web scraper。目前,它从http://www.dotamax.com(视频游戏DOTA 2的统计页面),并创建一个对象,其中包含获胜率、拾取率和代码分配给每个英雄的任意分数。JavaScript是有效的,但现在我迷上了在网页中使用代码。我在机器上创建了一个本地web服务器,这样我就可以在html文件中使用JavaScript文件,但我不确定使用JavaScript中的对象在html中创建表的最佳方式。任何方向都会很有帮助!这是我的JavaScript文件的代码,我想放在表中的对象是heroObjs。

var request = require('request');
var cheerio = require('cheerio');
// list that will iterate through every skill level. used in the url
skillLevels = {
  'Very high': 'vh',
  'High': 'h',
  'Normal': 'n'
};
heroes = ['pudge', 'windrunner', 'nevermore', 'earthshaker', 'lina','pudge',
   'queenofpain', 'invoker', 'antimage', 'juggernaut', 'alchemist',
   'doom_bringer', 'tusk', 'rubick', 'bounty_hunter', 'slark',
   'storm_spirit', 'ember_spirit', 'spectre', 'spirit_breaker', 'silencer',
   'legion_commander', 'lion', 'phantom_assassin', 'mirana', 'zuus',
   'undying', 'rattletrap', 'templar_assassin', 'bloodseeker',
   'witch_doctor', 'crystal_maiden', 'gyrocopter', 'dazzle','winter_wyvern',
   'necrolyte', 'ancient_apparition', 'ogre_magi', 'skeleton_king',
   'phantom_lancer', 'axe', 'magnataur', 'tiny', 'riki', 'slardar',
   'earth_spirit', 'leshrac', 'furion', 'sand_king', 'omniknight',
   'huskar', 'disruptor', 'tinker', 'ursa', 'bristleback', 'sniper',
   'venomancer', 'nyx_assassin', 'life_stealer', 'clinkz', 'vengefulspirit',
   'skywrath_mage', 'kunkka', 'lich', 'faceless_void', 'dark_seer', 'techies',
   'jakiro', 'abaddon', 'phoenix', 'sven', 'shadow_shaman', 'luna', 'viper',
   'enigma', 'shredder', 'weaver', 'tidehunter', 'night_stalker', 'medusa',
   'chaos_knight', 'puck', 'drow_ranger', 'centaur', 'keeper_of_the_light',
   'pugna', 'dragon_knight', 'warlock', 'morphling', 'broodmother','meepo', 'terrorblade', 'treant', 'razor', 'bane', 'batrider',
   'death_prophet', 'troll_warlord', 'wisp', 'shadow_demon', 'naga_siren',
   'obsidian_destroyer', 'enchantress', 'lone_druid', 'beastmaster',
   'lycan', 'oracle', 'brewmaster', 'elder_titan', 'visage', 'chen'
   ];
// creates a multidimensional object that holds hero stats
var heroObjs = {};
for (var i = 0; i < heroes.length; i++) {
   var hero = heroes[i];
   if (hero in heroObjs == false) {
     heroObjs[hero] = {
       "Very high": {
         "Pick Rate": null,
         "Win Rate": null,
         "Score": null
       },
       "High": {
         "Pick Rate": null,
         "Win Rate": null,
         "Score": null
       },
       "Normal": {
         "Pick Rate": null,
         "Win Rate": null,
         "Score": null
       },
     };
   }    
 }
for (skills in skillLevels) {
   var url = "http://www.dotamax.com/hero/played/?skill=" + skillLevels[skills];
   request(url, (function (skills) {
     return function (err, resp, body) {
       if (err)
         throw err;
        $ = cheerio.load(body);
       //creates the score and gets win rate and pick rate from dotamax.com
       //currently only fills score for very high skill bracket
       $("tbody tr").each(function (hero) {
         $(this).find('td div:contains("%")').each(function () {
           var containsPickRate = $(this).parent().parent().find("td").eq(1).toString();
      var containsHeroName = $(this).parent().parent().toString();
      var pickRateIndex = containsPickRate.indexOf('10px">') + 6;
      var endPickRateIndex = containsPickRate.indexOf('</div>');
      var heroNameIndex = containsHeroName.indexOf("detail/") + 7;
      var endHeroNameIndex = containsHeroName.indexOf('&apos;)" style');
      var heroName = containsHeroName.substring(heroNameIndex, endHeroNameIndex);
      var pickRate = containsPickRate.substring(pickRateIndex, endPickRateIndex);
      pickRate = pickRate.split(',').join("");
      var winRate = parseFloat($(this).text());
      pickRate = parseFloat(pickRate);
      if (heroName in heroObjs == true) {
        heroObjs[heroName][skills]["Pick Rate"] = pickRate;
        heroObjs[heroName][skills]["Win Rate"] = winRate;
        if (skills === "Very high") {
          var winRateCont = 1.4 * .01 * Math.pow(winRate, 2)
          var pickRateCont = .8 * ((10775 / (100 + 1090 * Math.pow(Math.E, -.000005 * pickRate))) - 8.3)
          heroObjs[heroName][skills]["Score"] = (pickRateCont + winRateCont)
        }
      }
    })
  });
}
   })(skills));
 }
 //waits 10 seconds to display heroObjs which is approximate time 
 //it takes for the previous function to fill heroObjs
 setTimeout(function () {
    console.log(heroObjs);
  }, 10000);

首先,您的最佳选择是使用一个已建立的Javascript框架来为您实现这一点。例如,jQuery和/或angular.js.

例如,使用angular.js,您只需执行以下操作:

<table>
  <tr data-ng-repeat="hero in heroObjs">
    <td>{{hero.attr1}}</td>
  </tr>
</table>

Angular将负责其余的工作。它将解析您的数据,并为您构建html。理解angular或jQuery这样的框架需要一段时间,但时间花得很好。维护您自己的函数库来执行类似的操作是一种巨大的时间浪费,而且您将花费更多的时间进行调试而不是构建。