我找到了一段纯JS代码,用于在文本中应用省略号。
function dotify(element) {
var limit = element.offsetTop + element.offsetHeight;
var dots = document.createElement('span');
if (element['data-inner'])
element.innerHTML = element['data-inner'];
else
element['data-inner'] = element.innerHTML;
dots.appendChild(document.createTextNode('...'));
element.style.overflow = 'hidden';
element.appendChild(dots);
while (dots.offsetTop + dots.offsetHeight > limit) {
dots.previousSibling.data = dots.previousSibling.data
.replace(/\W*\w+\W*$/, '')
}
}
当我将此代码应用于一个元素时,它就像一个魅力。但是,当我使用 each()
函数将其应用于具有相同类的每个元素时,出现未定义的错误。
jQuery(".product-description").each(function() {
dotify(jQuery(this));
onresize = function(){ setTimeout(function() { dotify(jQuery(this)); }, 100); };
});
以下作品:
test = jQuery(".product-description")[0]
dotify(test);
onresize = function(){ setTimeout(function() { dotify(test); }
最佳答案
您需要将 dom 元素引用传递给 dotify
,而不是 jQuery 对象引用。
jQuery(".product-description").each(function () {
var el = this;
dotify(el);
onresize = function () {
setTimeout(function () {
dotify(el);
}, 100);
};
});
注意:不确定代码中 onresize
函数的用途
关于javascript - 对同一类的每个元素运行 jQuery 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32393673/