使用Javascript对象和函数时字符串长度无效

时间:2019-03-30 20:23:37

标签: javascript html object

我正在尝试创建一个可以放入JavaScript对象的函数,以免一遍又一遍地重复使用html代码。

我有两个看起来像这样的对象:

var TannerTrailGrandCanyon = {
  name: "Tanner Trail Grand Canyon",
  lat: 36.0326,
  long: -111.8525,
  type: "backpacking", 
  //Title then link
  seekAdventure: ['22 Hours of Driving, 1.5 Days of Snowshoeing, Yosemite National Park!','https://www.seekadventure.net/d/79-22-hours-of-driving-1-5-days-of-snowshoeing-yosemite-nationa'],
  blogs: []
};

var BadgerPass = {
  name: "Badger Pass - Yosemite",
  lat: 36.0326,
  long: -111.8525,
  type: "backpacking", 
  //Title then link
  seekAdventure: ['22 Hours of Driving, 1.5 Days of Snowshoeing, Yosemite National Park!','https://www.seekadventure.net/d/79-22-hours-of-driving-1-5-days-of-snowshoeing-yosemite-nationa'],
  blogs: ['Snowshoeing to Dewey Point in Yosemite - Socal Hiker','https://socalhiker.net/snowshoeing-to-dewey-point-in-yosemite/']
};

然后将它们放入数组:

markers1 = [
  TannerTrailGrandCanyon,
  BadgerPass
]; 

然后我用来在Google地图上放置点。

然后,我创建了一个函数来构建将进入Google Map弹出气泡的html代码:

//put pop up bubble html together 
function BuildBubbleHTML(hike){
    html = "";
    html = html +'<h3>'  + hike.hikename + '</h3>';

    //If Seek Adventure Links Exist
    if(hike.seekAdventure.length > 0){
        seekAdventureHTML = '<p>Seek Adventure Links</p>';
        seekAdventureHTML = seekAdventureHTML + '<ul>'
        var i;
        for (i = 0; i < hike.seekAdventure.length; i+2) { 
            seekAdventureHTML = seekAdventureHTML + '<li>';
            seekAdventureHTML = seekAdventureHTML + '<a href="' + hike.seekAdventure[i+1] + '">';
            seekAdventureHTML = seekAdventureHTML + hike.seekAdventure[i] + '</a></li>';
        } 
        seekAdventureHTML = seekAdventureHTML + '</ul>';
        html = html + seekAdventureHTML;
    }

    //If Blog Links Exist
    if(hike.blogs.length > 0){
        blogHTML = '<p>Blog Links</p>';
        blogHTML = blogHTML + '<ul>'
        var i;
        for (i = 0; i < hike.blogs.length; i+2) { 
            blogHTML = blogHTML + '<li>';
            blogHTML = blogHTML + '<a href="' + hike.blogs[i+1] + '">';
            blogHTML = blogHTML + hike.blogs[i] + '</a></li>';
        } 
        blogHTML = blogHTML + '</ul>';
        html = html + blogHTML;
    }


    return html;
};

执行代码时出现此错误:

  

mapCode.js:250未捕获(承诺)RangeError:无效的字符串长度

问题出在以下一行:seekAdventureHTML = seekAdventureHTML + '<a href="' + hike.seekAdventure[i+1] + '">';

我认为在下一行中抓住i之前,它可能无法抓住i + 1,但是我交换了两者,但这仍然行不通。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

在这里看起来像错字了

        for (i = 0; i < hike.seekAdventure.length; i+2) {

我假设您的意思是i++(或者可能是i+=2),而不是i+2。我的值永远不会改变,循环是无限的,并不断添加到字符串中-脚本只是在RAM中用完了。