我正在尝试解析诗歌,使每一行都是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]);
}
这样的东西能满足你的需求吗?
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
$(".tile-set").html(""); // Set the html to be an empty string so we can concatenate
for (a in tileset) {
tileset[a] = tileset[a].split(" "); // creating a nested array of words
for (b in tileset[a]) {
$(".tile-set").html( $(".tile-set").html() + "<span class='tile'>" + tileset[a][b] + "</span>" );
};
};
}
tilify();
}
您可以得到这个输出Thebootisfamoustotheearth, morefamousthanthedressshoe, whichisfamousonlytofloors
,但您可以修改<span></span>
标记以按照您想要的方式工作。
问题是试图将嵌套数组传递到.html()
方法中(感谢Phil)。我将文本传递到tilesetBody
变量中,并使用该变量。
function tilify () {
var tiletext = $(".tile-set").html().trim().replace("<br>"," ").replace(/ +(?= )/g," ").replace(/,/g, "").replace(/./g,"").replace(/;/g,"");
var tilesetBody = "";
tileset = tiletext.split(" ");
for (a in tileset) {
tileset[a] = tileset[a].split(" ");
for (b in tileset[a]) {
if (tileset[a][b] != "") {
tileset[a][b] = "<span class='tile'>" + tileset[a][b] + "</span> ";
tilesetBody += tileset[a][b];
}
};
tilesetBody += "<br>";
};
$(".tile-set").html(tilesetBody);
}