我需要检查div是否为空并忽略空格。
如果您在下面的div中键入一个或多个空格,然后单击按钮,它将记录为“空”而不是“不为空”。
$('button').on('click', function(){
let a = $('#wrap').html();
if(a == '' || a.trim() == ''){console.log('empty');}
else{console.log('not empty');}
});
.wrap{
background:gold;
min-height:25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap' id='wrap' contenteditable></div>
<button>CLICK</button>
答案 0 :(得分:1)
您应该改用.text()
。同样,对空字符串的第一次检查是多余的。此问题的根本原因是空格在HTML中表示为
,如果您console.log(a)
可以看到。
$('button').on('click', function() {
let a = $('#wrap').text();
if (a.trim() == '') {//or simply, if(!a.trim()){
console.log('empty');
} else {
console.log('not empty');
}
});
.wrap {
background: gold;
min-height: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap' id='wrap' contenteditable></div>
<button>CLICK</button>
答案 1 :(得分:1)
您可以简单地使用jQuery .text()来检查div中任何文本的长度。这样可以避免(不计算)空格。
Bitmap GetWindowBitmap(IntPtr hWnd) {
RECT bounds;
if (!GetWindowRect(hWnd, out bounds))
throw new Win32Exception();
var bmp = new Bitmap(bounds.right - bounds.left, bounds.bottom - bounds.top);
using (var g = Graphics.FromImage(bmp))
{
IntPtr dc = IntPtr.Zero;
try
{
dc = g.GetHdc();
bool success = PrintWindow(hWnd, dc, PrintWindowDrawingOptions.PW_RENDERFULLCONTENT /* 0x00000002 */);
if (!success)
throw new Win32Exception();
}
finally
{
if (dc != IntPtr.Zero)
g.ReleaseHdc(dc);
}
}
return bmp;
}
的工作方式是也将计算空格。
运行下面的代码段。
.html()
$('button').on('click', function() {
let a = $('#wrap').text();
if (a == '' || a.trim() == '') {
console.log('empty');
} else {
console.log('not empty');
}
});
.wrap {
background: gold;
min-height: 25px;
}