如何计算javascript html字符串变量中的行数

How to count number of lines in javascript html string variable

本文关键字:变量 字符串 html javascript 何计算 计算      更新时间:2023-09-26

我有一个带有html字符串数据的javascript变量,格式如下

var html_string = '<p class="MsoListParagraph" style="margin-left:28.5pt;mso-add-space:auto;text-indent:-28.5pt;mso-list:l0 level2 lfo1;tab-stops:list 28.5pt"><!--[if !supportLists]--><b><span lang="EN-US">1.1<span style="font-weight: normal; font-stretch: normal; font-size: 7pt; line-height:normal; font-family: Times New Roman;"></span></span></b><!--[endif]--><b><span lang="EN-US">Purpose of the Document<o:p></o:p></span></b></p><p class="MsoNormal" style="margin-left:28.5pt;tab-stops:80.25pt"><span lang="EN-US">This document helps to understand the design aspects of the ASSMail web based project. This document details the technical specification for the project.</span></p>';

我试着根据break语句进行计数,但没有成功。

我想计算在浏览器视图的这个html字符串中找到的行数。有谁能帮忙做这个过程吗?

根据您的后续评论,您可以使用DOMParser解析内容,然后了解段落数:

var parser = new DOMParser(),
    doc = parser.parseFromString(html_string, "text/html"),
    paragraphs = doc.querySelectorAll('p').length;
alert('there is '+paragraphs+' paragraphs');

演示->http://jsfiddle.net/nfwy006u/1/

如果正确解释Question,请尝试从html_string创建jQuery对象,使用.filter()选择p元素,返回的jQuery对象的.length属性用于原始字符串中p元素的数量

$(html_string).filter("p").length

var html_string = '<p class="MsoListParagraph" style="margin-left:28.5pt;mso-add-space:auto;text-indent:-28.5pt;mso-list:l0 level2 lfo1;tab-stops:list 28.5pt"><!--[if !supportLists]--><b><span lang="EN-US">1.1<span style="font-weight: normal; font-stretch: normal; font-size: 7pt; line-height:normal; font-family: Times New Roman;"></span></span></b><!--[endif]--><b><span lang="EN-US">Purpose of the Document<o:p></o:p></span></b></p><p class="MsoNormal" style="margin-left:28.5pt;tab-stops:80.25pt"><span lang="EN-US">This document helps to understand the design aspects of the ASSMail web based project. This document details the technical specification for the project.</span></p>';
var html = $(html_string);
html.appendTo("body");
console.log(html.filter("p").length)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

找到元素的高度-文本以元素的MDN维度显示,然后除以字体高度。

您可以获得div 的高度

jQuery("#id-of-your-div").height()

然后把它折成一行的高度,它将通过的行数

例如:

jQuery("#id-of-your-div").height()/20

如果变量中的html要更改,我想很难得到有多少行,因为有些标记是内联的,有些标记是块的。Block元素还可以开始一个新行(或者可以是将内联元素设置为Block的内联css),而不仅仅是<br>标记。

所以我假设你已经得到了div的高度。下面是一个想法:你可以在没有显示的页面上插入你的html,并用一些代码来获得它的高度,比如:

jQuery("#id-of-your-div").height()