我有一个textarea,我想得到它的值,然后计算开始和结束div的数量。我在使用渲染的HMTL时遇到问题,即使它已被全部转义,我仍然会遇到这样的错误:Uncaught Error: Syntax error, unrecognized expression: <div>This is a test</div>
将<div>This is a test</div>
输入textarea。
我希望能够将HTML标记保留在内容中,即能够搜索与<div
<div
HTML
<h3>Paste your code in here</h3>
<textarea name="code" id="code" cols="30" rows="10"></textarea>
<p>
<a href="#" class="test-code-btn">Go for it!</a>
</p>
JS
$('.test-code-btn').on('click', function(){
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
var res = escapeHtml($('#code').val());
console.log('res = ' + res);
var openDivs = $(res).find('<div').length;
var closeDivs = $(res).find('</div').length;
console.log('openDivs: ' + openDivs + ', closeDivs: ' + closeDivs);
});
答案 0 :(得分:1)
这可以让你开始正确!
适用于CodePen。
var openCounter=0;
var closeCounter=0;
var raw = $('#code').val();
for(i=0;i<raw.length;i++){
if( raw.charAt(i)=="<" ){
if( raw.charAt(i+1)=="\/" ){
//console.log("One close tag");
closeCounter++;
}else{
//console.log("One open tag");
openCounter++;
}
}
}
console.log(openCounter+" opening tags and "+closeCounter+" closing tags.");