2017-10-11 161 views
0

如果我添加更多的ID与相同的元素缩短在同一个页面不起作用,只剪切第一个但其他人不。缩短多个项目使用相同的ID的错误

$(function() { 
 
    var maxlength = 10; 
 
    var dots = $('#original').text().length>maxlength?'...':''; 
 
    var hello = $('#original').text().length>maxlength?$('#original').text().substring(0,maxlength).replace(/\W\w+\s*(\W*)$/, '$1'):$('#original').text(); 
 
    $('#original').before('<h2 id="result">'+hello+dots+'</h2>') 
 
    $('#original').text($('#original').text().substring(hello.length)) 
 
    .css('display','none') 
 
    .appendTo('#result'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h2 id="original">php 7 basic</h2> 
 

 
<h2 id="original">Another text from another container</h2> 
 

 
<h2 id="original">Another text from another container two</h2>

验证HTML的另一个错误是不应该被重复的ID应该每页只能使用一次。

我该如何从ID迁移到类并修复上述错误?

+1

*“我怎样才能从ID迁移到课堂并修复所提到的错误?”*您的研究成果是什么?你知道如何给元素上课,对吧?以及如何按类选择元素?如果没有,你知道在哪里可以找到这些信息......? –

+0

你可以写一个脚本,可以将你的id转换成类,但老实说,这将需要更长的时间,而不是逐行。在上面的示例中,只需将“id”替换为“class”即可完成。你将需要修正你的jQuery包,因为各种'$('。original')'调用都会返回多个结果。尝试使用'this'。编程是关于试验和学习。 – nurdyguy

+2

@nurdyguy我已经尝试了你说的,但它现在不工作,它只显示省略号,但不显示文本https://jsfiddle.net/2vo2tq7f/ – AmLy

回答

1

您可以使用每个遍历在JQuery的类集合:

var maxlength = 10; 
$('.original').each(function(i, el) { 

    var dots = $(el).text().length>maxlength?'...':''; 
    var hello = $(el).text().length>maxlength?$(el).text().substring(0,maxlength).replace(/\W\w+\s*(\W*)$/, '$1'):$(el).text(); 
    $(el).before('<h2 id="result">'+hello+dots+'</h2>') 
    $(el).text($(el).text().substring(hello.length)) 
    .css('display','none') 
    .appendTo('#result'); 
}); 

然后就是改变你的id到类:

<h2 class="original">php 7 basic</h2> 

<h2 class="original">Another text from another container</h2> 

<h2 class="original">Another text from another container two</h2> 

Codepen here

+0

有一个错字,一个el.text(),意思是是$(el).text(),我已经修复了它的答案,这里有一个更新的小提琴:https://jsfiddle.net/ohjexf7c/ – delinear

+0

用浏览器的开发工具检查的代码应该像这样显示https ://jsfiddle.net/mhyem450/1/ – AmLy

+0

@AmLy看到了,我为你感到难过,所以在这里,我已经修复了delinear的代码,以满足你的需求:https://codepen.io/anon/pen/wrxBmE (这个问题原来是这个前一个问题的延续:https://stackoverflow.com/questions/46679311/how-to-truncate-words-with-jquery-without-cutting-words-in-source-code)。 ..线性给你一个很好的尝试,只需要一点点修复 –

0

你可以做while循环遍历所有具有相同id的元素,为它们提供所有唯一(顺序)的id,并为它们分配一个类:

var i = 1; 
while(element = document.getElementById('original')) { 
    element.setAttribute('id','original-'+i) 
    element.setAttribute('class','original'); 
    i++; 
} 
相关问题