我试图解析诗歌,以便每一行都是tileset数组中的一项,每个单词都是该数组(2个级别)中的一项。我希望每个单词都在一个范围内,并且(以后)每个新行之间要有一个分隔符。

当我遍历更改单个单词(tileset [a] [b])的值以使其包裹在跨度中时,我遇到了问题。

这是代码:

function tilify (){
  var tiletext = $(".tile-set").html().trim().replace("<br>","  ").replace(/ +(?= )/g,"  "); // trimming whitespace and regulating newline format to a double-space
  tileset = tiletext.split("  "); // creating an array of lines
  for (a in tileset) {
    tileset[a] = tileset[a].split(" "); // creating a nested array of words
    for (b in tileset[a]) {
      tileset[a][b] = "<span class='tile'>" + tileset[a][b] + "</span>";  // returns error
    };
  };
  $(".tile-set").html(tileset);
}

tilify();


返回的错误是Uncaught TypeError: e.replace is not a function

我尝试了几种循环语法。我还尝试摆脱了以防万一的.replace方法。如果我将第一个数组的元素包装在span标签中,而不是第二个标签,则可以使用。

我有jquery和jqueryUI运行。

同样,这是我遇到的麻烦:

for (b in tileset[a]) {
  tileset[a][b] = "<span class='tile'>" + tileset[a][b] + "</span>";  // returns error
};


这是HTML的主体

<div class='container'>
  <p class='tile-set'>
    The boot is famous to the earth,
    more famous than the dress shoe,
    which is famous only to floors.
  </p>
</div>

最佳答案

您的代码在$(".tile-set").html(tileset);行上中断,因为$ .html()无法处理嵌套数组。它正在寻找字符串数组。如果要在一个元素中包含所有内容,则需要另一个for循环,然后像这样将整个内容连接起来:
for(a in tileset) { $(".tile-set").html($(".tile-set").html()+tileset[a]); }

10-05 23:02