如何计算javascript html字符串变量中的行数
How to count number of lines in javascript html string variable
我有一个带有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()
相关文章:
- 使用JSON文件中的变量(字符串)填充文本区域
- 如何向变量字符串添加更多值
- jquery将变量字符串作为ID's
- 如何用HTML和相应的引号形成变量字符串
- PHP 反序列化 JS 序列化的变量字符串
- Javascript 不传递整个变量字符串
- 带有变量字符串的索引
- 如何将表单类值合并到新的变量字符串中
- 在 JavaScript 中将变量字符串括起来
- jQuery:用变量字符串替换(连接的)按钮值
- "[对象对象]”;在警报提示中使用时替换变量字符串
- 通过变量字符串定义对象
- 无法在Javascript中连接字符串+变量+字符串
- Fancybox-是否可以使用javascript变量字符串作为HTML内容
- 从变量字符串应用条件
- 如何在pug中插入变量字符串
- Javascript -在变量字符串中捕获名称
- 不能把变量(字符串)在javascript innerhtml
- 用变量字符串调用React类
- 使用 Browserify/Babel/node.js您是否需要一个基于变量字符串的文件