我正在制作一个插件,如果太长,可以在其中缩短论坛索引中每个条目的标题。但是,这比我预期的要难得多。
一切正常,除了我需要实际将项目打印到DOM上的那部分。
我收到此错误:
Uncaught TypeError: undefined is not a function
这是我的代码,并附带了一些注释,以向您展示其工作方式。
var minimize = function() {
$('.segment').each(function(){
var title_box = $(this).children('.title');
// Selects the container of the title.
var title = $(this).children('.title').text().trim();
// Takes the child title of the each .segment class and selects its innards.
console.log(title);
var res = title.split("");
// Splits the text into an array.
console.log(res);
var fragment = [];
// initializing the empty array
for (x = 0; x < 4; x++) {
fragment.push(res[x]);
console.log(fragment);
// Loops through to make sure it's not more than 5 characters long
};
var final = fragment.join("");
// Joins the broken up string together.
title_box.empty();
final.appendTo(title_box);
});
};
您认为我做错了什么?如果我还有其他方法可以使此代码更高效,请不要犹豫告诉我。
在这里,您定义fragment
为一个数组:
var fragment = [];
然后,将其填充并执行以下操作:
var final = fragment.join("");
阅读关于array.join的文档,以了解该功能的作用。简而言之,它将您的数组连接到一个string
所以现在当您执行此操作时:
final.appendTo(title_box);
您得到您的信息,TypeError
因为字符串没有appendTo
方法
您可能想要的是一个要调用的jquery对象appendTo
。
也许您的意思是:
title_box.text(final);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句