对每个数组分区重复Javascript结果



我已经对stackoverflow进行了全面扫描,以寻找有关我的查询的解决方案,结果发布了一个问题。请有人帮助我,我的技能是PHP,我不是100%流利的JS/jQuery。

下面的代码允许div文本在超过8个字符时被缩短。

<div id="theText">Very long text here</div>
<script>
function cutString(id){    
var text = document.getElementById(id).innerHTML;         
var charsToCutTo = 8;
if(text.length>charsToCutTo){
var strShort = "";
for(i = 0; i < charsToCutTo; i++){
strShort += text[i];
}
document.getElementById(id).title = "text";
document.getElementById(id).innerHTML = strShort + "...";
}            
};
cutString('theText'); 
</script>

然而,我现在正试图根据下面的代码在多个Div上做到这一点,我认为我应该使用的方法是数组,下面是一个不起作用的版本,但我正在寻找指导的概念。

感谢您的帮助。

<div id="theText[]">Very long text here</div> 
<div id="theText[]">Even more long text here</div> 
<script>
function cutString(id){    
var text = document.getElementById(id).innerHTML;         
var charsToCutTo = 8;
if(text.length>charsToCutTo){
var strShort = "";
for(i = 0; i < charsToCutTo; i++){
strShort += text[i];
}
document.getElementById(id).title = "text";
document.getElementById(id).innerHTML = strShort + "...";
}            
};
cutString('theText[]'); 
</script>

我认为Ken Lee正确回答了这个问题,但我认为OP希望采取更动态的方法,在这种情况下,我建议从ID转移到类中,因为它们(类(更适合迭代,如下所示:

<div class="longText">Very long text here</div>
<div class="longText">Very long text here as well</div>
<div class="longText">And the text here is even longer</div>
<script>
function cutString(element){    
var text = element.innerText; // We fetch innerText to omit any HTML from the length check       
var charsToCutTo = 8;
if(text.length>charsToCutTo){
var strShort = "";
for(i = 0; i < charsToCutTo; i++){
strShort += text[i];
}
element.title = text; // we set the value of title to allow tooltip hovering of full text
element.innerText = strShort + "...";
}            
}
var longTextElems = document.getElementsByClassName('longText'); // This will return a collection of HTML elements
console.log(longTextElems.length);
for(count = 0; count < longTextElems.length; count++) {
cutString(longTextElems.item(count));
}
</script>

我已经包含了一个JSFiddle

或者,如果你正在寻找基于宽度的基本概要,CSS3已经满足了这一点:Ellipsis溢出

其中一种方法是指定数组(0,1,2…(的索引

因此,在您的情况下,您需要处理Text[0]和Text[1]。

这是正在工作的代码:

<div id="theText[0]">Very long text here</div> 
<div id="theText[1]">Even more long text here</div> 
<script>
function cutString(id){    
var text = document.getElementById(id).innerHTML;         
var charsToCutTo = 8;
if(text.length>charsToCutTo){
var strShort = "";
for(i = 0; i < charsToCutTo; i++){
strShort += text[i];
}
document.getElementById(id).title = "text";
document.getElementById(id).innerHTML = strShort + "...";
}            
};
cutString('theText[0]'); 
cutString('theText[1]'); 
</script>

最新更新