2016-10-03 152 views
1

我正在使用表情符号。设置为空后,我只想在textarea上设置值。但它不起作用。 我的代码是在这里,我无法设置Textarea为空

$('.tooltiptext .emoticon').click(function() { 
     $in = $(this); 
     console.log($in); 
     setTimeout(function() { 
      var dataText = $("#text").val(); 
      $('#text').append(dataText + $.emoticons.replace($in.html())); 
      var dataCode = $in.context.innerText; 
      console.log(dataCode); 
      var dataTextArea = $("textarea").val(); 
      console.log(dataTextArea + dataCode); 
      //$('#textarea').html(''); 
      $('#textarea').empty();// it not working 
      console.log($('#textarea').val()); 
      $('#textarea').append(dataTextArea + dataCode + ' '); 

     }, 100); 

    }); 

    $('textarea').on('keypress', function(e) { 

     if (e.which == 32 || e.which == 8) { 
      $in = $(this); 
      setTimeout(function() { 
       $("#text").html($.emoticons.replace($in.val())); 
      }, 100); 
     } 

    }); 

回答

3

使用val(),不text()html()empty(),以清除textarea的价值:

$('#textarea').val(''); 

同样的,用它来设置的值,而不是append()

$('#textarea').val(dataTextArea + dataCode + ' '); 

您的也是如此元素 - 假设它是inputtextarea。您的代码的简化版本会是这样的:

$('.tooltiptext .emoticon').click(function() { 
    $in = $(this); 

    setTimeout(function() { 
     $('#text').val(function(i, v) { 
      return v + $.emoticons.replace($in.html()); 
     }); 

     $('#textarea').val(function(i, v) { 
      return v + $in.context.innerText + ' '; 
     }); 
    }, 100); 
}); 
+0

感谢它的工作原理。但为什么没有.append工作? –

+0

因为你正在设置底层元素的'value'属性。 append()用于在DOM中创建一个全新的元素。 –