我试图动态地检测文本区域是否为空。我这样做是为了只有当文本区域中输入文本时,我才能显示一个发送按钮。
我尝试了下面的代码,但它不起作用。
var text = document.getElementById("text").value;
if (text !== ''){
    alert("works");
    document.getElementById("sendicon1").style.display = "none";         
    document.getElementById("sendicon2").style.display = "inline";         
}
else{
    alert("not working");
    document.getElementById("sendicon2").style.display = "none";         
    document.getElementById("sendicon1").style.display = "inline";
}发布于 2015-09-08 15:00:23
使用input事件非常容易。
var textarea = document.getElementById("text");
textarea.addEventListener('input', hideOnEmpty);
function hideOnEmpty() {
    var text = this.value;
    if (text !== ''){
        alert("works");
        document.getElementById("sendicon1").style.display = "none";         
        document.getElementById("sendicon2").style.display = "inline";         
    }
    else{
        alert("not working");
        document.getElementById("sendicon2").style.display = "none";         
        document.getElementById("sendicon1").style.display = "inline";
    }
}有关更多细节,请参见输入事件文档(MDN,W3schools)。每次文本区域的内容发生变化时,此代码都会触发hideOnEmpty函数。
当心--这段代码在IE8或更低版本中不能工作,并且可能无法检测到IE9中的删除(但是没有可靠的方法来检查输入是否在IE9中不进行轮询而更改)。
发布于 2015-09-08 14:57:35
您是将该代码放入onkeyup或onchange函数中吗?你可以这样做:
window.onload = function() { 
  var text = document.getElementById("text");
  var func = function() { 
    if (text.value !== '') {
      alert("works");
      document.getElementById("sendicon1").style.display = "none";         
      document.getElementById("sendicon2").style.display = "inline";         
    } else {
      alert("not working");
      document.getElementById("sendicon2").style.display = "none";         
      document.getElementById("sendicon1").style.display = "inline";       
    }
  }
  text.onkeyup = func;
  text.onchange = func;
}您不需要onkeyup和onchange,这取决于您何时寻找它开火。在您将焦点移除(模糊)之后,onkeyup将在文本区域内按下每个键之后。
发布于 2015-09-08 14:56:07
您还没有将jQuery作为依赖项列出,但这绝对是它会有用的一个方面。
$('#text').on('input propertychange', function () {
    if ($(this).val() !== "") {
       $("#sendicon1").hide();
       $("#sendicon2").show();
    }
    else {
       $("#sendicon2").hide();
       $("#sendicon1").show();    
    }
});input事件将检测到textarea的所有更改-按键、复制和粘贴等等。
https://stackoverflow.com/questions/32460928
复制相似问题