2017-10-11 147 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++; 
} 
相關問題