window.onload = function () { var txt1 = document.getElementById('txt1'), txt2 = document.getElementById('txt2'), btn1 = document.getElementById('btn1'), btn2 = document.getElementById('btn2'); btn1.onclick = function () { return txt1.value ? true : alert('输入不能为空'); } btn2.onclick = function () { return txt2.value.replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g,'') ? true : alert('输入不能为空'); } }
<h2>不考虑空格</h2> <input type='text' id='txt1'/> <button type='button' id='btn1'>click</button> <h2>过滤空格</h2> <input type='text' id='txt2'/> <button type='button' id='btn2'>click</button>