我想捕获<textarea>. 就像键入任何字符(删除、退格)或鼠标单击并粘贴或剪切。是否有可以触发所有这些事件的 jQuery 事件?
我尝试了更改事件,但它仅在从组件中退出后才触发回调。
使用:如果 a<textarea>包含任何文本,我想启用一个按钮。
我想捕获<textarea>. 就像键入任何字符(删除、退格)或鼠标单击并粘贴或剪切。是否有可以触发所有这些事件的 jQuery 事件?
我尝试了更改事件,但它仅在从组件中退出后才触发回调。
使用:如果 a<textarea>包含任何文本,我想启用一个按钮。
试试这个:
$('#textareaID').bind('input propertychange', function() {
      $("#yourBtnID").hide();
      if(this.value.length){
        $("#yourBtnID").show();
      }
});
这适用于您所做的任何更改、打字、剪切、粘贴。
bind已弃用。使用on:
$("#textarea").on('change keyup paste', function() {
    // your code here
});
注意:上面的代码将触发多次,每个匹配的触发器类型触发一次。要解决这个问题,请执行以下操作:
var oldVal = "";
$("#textarea").on("change keyup paste", function() {
    var currentVal = $(this).val();
    if(currentVal == oldVal) {
        return; //check to prevent multiple simultaneous triggers
    }
    oldVal = currentVal;
    //action to be performed on textarea changed
    alert("changed!");
});
使用input事件。
var button = $("#buttonId");
$("#textareaID").on('input',function(e){
  if(e.target.value === ''){
    // Textarea has no value
    button.hide();
  } else {
    // Textarea has a value
    button.show();
  }
});
这个问题需要一个最新的答案,有来源。这才是真正有效的(虽然你不必相信我的话):
// Storing this jQuery object outside of the event callback 
// prevents jQuery from having to search the DOM for it again
// every time an event is fired.
var $myButton = $("#buttonID")
// input           :: for all modern browsers [1]
// selectionchange :: for IE9 [2]
// propertychange  :: for <IE9 [3]
$('#textareaID').on('input selectionchange propertychange', function() {
  // This is the correct way to enable/disabled a button in jQuery [4]
  $myButton.prop('disabled', this.value.length === 0)
}
1:https  : //developer.mozilla.org/en-US/docs/Web/Events/input#Browser_compatibility
 
2:当我们点击 BACKSPACE / DEL / do CUT 
 
3时,IE9 中的 oninput 不会触发:https://msdn .microsoft.com/en-us/library/ms536956(v=vs.85).aspx 
 
4:http : //api.jquery.com/prop/#prop-propertyName-function
但是,对于可以在整个项目中使用的更全局的解决方案,我建议使用textchange jQuery 插件来获得一个新的、跨浏览器兼容的textchange事件。它是由为 Facebook 的 ReactJS实现等效事件的同一个人开发onChange的,他们几乎将其用于整个网站。而且我认为可以肯定地说,如果它对 Facebook 来说是一个足够强大的解决方案,那么它对你来说可能也足够强大。:-)
更新:如果您碰巧需要 Internet Explorer 中的拖放支持等功能,您可能需要查看pandell最近更新的jquery-splendid-textchange.
现在的问题是与JQuery的,它只是供参考。
let textareaID = document.getElementById('textareaID');
let yourBtnID = document.getElementById('yourBtnID');
textareaID.addEventListener('input', function() {
    yourBtnID.style.display = 'none';
    if (textareaID.value.length) {
        yourBtnID.style.display = 'inline-block';
    }
});
<textarea id="textareaID"></textarea>
<button id="yourBtnID" style="display: none;">click me</div>