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