注意:最初将此列为内存泄漏。在深入研究之后,我发现这不是内存问题。这只是一个非常慢的脚本。任何提高速度的建议都将不胜感激。
另一个注意:在进一步研究之后,我发现FF不支持任何类型的CSS格式化溢出文本。该黑客攻击有hack和workaround ......但这不是一个合适的解决方案。
我已经投票并加入了mozilla的particular bug电子邮件列表。它差不多六年了,所以我决定用户现在必须处理它。至少这不是我们产品的常见情况。
原帖:
脚本截断元素的值并附加'...',同时其scrollWidth大于它的offsetWidth。 (例如,“LastName,VeryLongFirstName”的值将更改为“LastName,Ver ...”,具体取决于列的宽度)
var eTable = document.getElementById(this._eDiv.id + "_tbl");
//...lots of code here...
//function called that gets all cells in a table, loops through them and clips the text
addEventListenerEx(window, "load", function() {
var aCells = eTable.getElementsByTagName("DIV");
window.alert(aCells.length);
//When aCells is length of 100, we're ok...but when it's big (like 3,000) I have problems
for (var i = 0; i < aCells.length; i++){
Grid.clipText(aCells[i]);
}
}, false);
//...lots of code here...
//This is the function doing the actual clipping
Grid.clipText = function (oDiv) {
//for tooltip
var oCurDiv;
var oTagA;
var sToolTip;
if (oDiv.firstChild) {
if (oDiv.firstChild.firstChild){
oCurDiv = oDiv.firstChild;
while (oCurDiv) {
if (is.ie) {
oTagA = oCurDiv;
} else {
// there are some different between IE & FireFox.
oTagA = oCurDiv.firstChild.parentNode;
}
if (oTagA.tagName == "A") {
sToolTip = oTagA.innerHTML;
if (sToolTip.indexOf('<b>') > 0) {
sToolTip = sToolTip.replace('<b>',"");
sToolTip = sToolTip.replace('</b>',"");
}
if (sToolTip.indexOf('<B>') > 0) {
sToolTip = sToolTip.replace('<B>',"");
sToolTip = sToolTip.replace('</B>',"");
}
oTagA.parentNode.title = convertHTMLToText(sToolTip);
}
oCurDiv = oCurDiv.nextSibling;
}
} else {
oDiv.title = convertHTMLToText(oDiv.innerHTML);
}
}
//NOTE: Additional steps to take for non-IE browsers
if (!is.ie) {
var oText = oDiv;
while (oText.nodeType != 3) {
oText = oText.firstChild;
}
var sDisplayText = oText.nodeValue;
if (sDisplayText.length < 3) return;
var lastThree;
sDisplayText = sDisplayText.slice(0, parseInt(oDiv.offsetWidth / 5));
oText.nodeValue = sDisplayText + "...";
//NOTE: Bad things happen here because of this loop
while (oDiv.scrollWidth > oDiv.offsetWidth && sDisplayText != "") {
lastThree = sDisplayText.slice(-3);
sDisplayText = sDisplayText.slice(0, sDisplayText.length - 3);
oText.nodeValue = sDisplayText + "...";
}
oText.nodeValue = sDisplayText + lastThree.slice(0, 1) + "...";
while (oDiv.scrollWidth > oDiv.offsetWidth && sDisplayText != "") {
oText.nodeValue = sDisplayText + "...";
}
}
代码有效。但是,问题是在页面上加载表后会一遍又一遍地调用它。当表格很大(> 1,500个单元格)时,就会出现问题。
所以,我真的在寻找一种方法来使这个样本(尤其是WHILE循环)更有效率。
答案 0 :(得分:0)
这一切都不会自行泄漏。您可能正在关闭oText,是否可以显示周围的代码?
顺便说一下,这是一种更有效的方法:
http://jsfiddle.net/cwolves/hZqyj/
如果你真的想继续这样做,你可以通过取字符串的长度并乘以它需要的比例宽度来估算截止点......
e.g。如果字符串是100个字符并且它应该是2倍,则将其切换为50个字符并重新检查。或者您可以实现二进制“搜索”算法以获得正确的长度。
答案 1 :(得分:0)
解决问题的方法来自基本算术cross multiplication
我在一个更受欢迎的stackoverflow thread中更详细地讨论了这个主题。