p標籤排序的話,我需要我的<p></p>
標籤內排序的話,所以當我這樣做:從HTML收集
var paragraphs = document.getElementsByTagName("p");
我得到的HTML集合。
在這一點上,我不知道如何繼續。如何從集合中獲取單個段落並對它們進行排序?
感謝您的幫助。
p標籤排序的話,我需要我的<p></p>
標籤內排序的話,所以當我這樣做:從HTML收集
var paragraphs = document.getElementsByTagName("p");
我得到的HTML集合。
在這一點上,我不知道如何繼續。如何從集合中獲取單個段落並對它們進行排序?
感謝您的幫助。
如果您將html嵌套在<p>
標記中,這會變得更復雜,但您可以將文本拆分爲字符串數組,然後sort the array。
這裏是顯示這個整體提琴:https://jsfiddle.net/tuc2d5f1/9/
這裏是基本的JS代碼。它沒有考慮節點內的html,也沒有複雜的字符替換。
for (var i in paragraphs) {
if (!paragraphs.hasOwnProperty(i)) continue;
// skip this iteration if it's not an actual element
console.log("Starting paragraph: " + i);
var text = paragraphs[i].innerHTML.toString().toLowerCase();
// get the text of the node
text = text.trim().replace(".", "");
// you need to remove special chars. Regex would be best
var txtAry = text.split(" "); // split to an array based on spaces
// you should first replace all newline/return chars with spaces
txtAry.sort(); // this is an array of strings in alphabetical order
console.log(txtAry);
}
getElementsByTagName
返回包含HTML集合的類似數組的對象。您需要循環瀏覽這些項目並從中提取html
var paragraphs = document.getElementsByTagName("p");
var html;
for (var i=0; i<paragraphs.length; i++) {
/* cache plain string */
html = paragraphs[i].innerHTML
/* convert into an array, sort it as an array, convert back to string */
html = html.split('').sort().join('');
console.log(html);
}
反對票是b/c,您需要顯示您已嘗試達到這一點,然後發佈一個失敗代碼的小例子。 – flyer
聽起來像作業 –
@ZachM。所以我有一個問題,我不能在這裏問一個問題?難道你沒有什麼更有趣的事情比嘮叨嗎? – grabnem