jquery
  • asp.net-mvc
  • textarea
  • 2010-06-15 135 views 2 likes 
    2

    文本区域的样子:JQuery。为什么我不能在textarea中插入html img标签?

    <textarea id="MessageContent" name="MessageContent"></textarea> 
    

    JQuery的样子:

    $("#insert").live("click", function() { 
          var t = "<img width='" + result.width + "' height='" + result.height + "' alt='" + result.descr + "' src='/Images/" + result.message + "' />"; 
          $("#MessageContent").html($("#MessageContent").html() + t); 
          $("#MessageContent").focus(); 
    
          $("#backgroundPopup").fadeOut("fast"); 
          $("#popupContact").fadeOut("fast"); 
         });  //live 
    

    我可以插入简单的文本,但不能将任何HTML标记。

    回答

    3

    你想用.val()这里,而不是.html()设置<textarea>的价值(否则该值没有编码,或正确使用),像这样:

    $("#insert").live("click", function() { 
        var t = "<img width='" + result.width + "' height='" + result.height + "' alt='" + result.descr + "' src='/Images/" + result.message + "' />"; 
        $("#MessageContent").val($("#MessageContent").val() + t); 
        $("#MessageContent").focus(); 
    
        $("#backgroundPopup").fadeOut("fast"); 
        $("#popupContact").fadeOut("fast"); 
    }); 
    

    您也可以缩短一bit by passing a function to .val(),like this:

    $("#insert").live("click", function() { 
        $("#MessageContent").val(function(i, val) { 
        return val + "<img width='" + result.width + "' height='" + result.height + "' alt='" + result.descr + "' src='/Images/" + result.message + "' />"; 
        }).focus(); 
        $("#backgroundPopup").fadeOut("fast"); 
        $("#popupContact").fadeOut("fast"); 
    }); 
    
    相关问题