javascript
  • asp.net-mvc-3
  • jquery
  • 2012-03-11 35 views 0 likes 
    0

    我使用ajaxForm來上傳圖像。在成功上傳我上傳圖像div添加在頁面上:如何從javascript中將頁面添加到html頁面,但不是在javascript中對其進行硬編碼

    $("#ajaxUploadForm").ajaxForm({ 
          iframe: true, 
          dataType: "json", 
    ... 
    success: function (result) { 
    $("#imageList").prepend('<img src=' + result.message + '/>'); 
    

    現在,我就在想,這不是聰明地把這種硬編碼在JavaScript代碼<img/>標籤。
    在prepend()函數中放置圖像但不使用img標記的最佳方法是什麼?

    +0

    爲什麼不聰明? – epascarello 2012-03-11 13:13:38

    回答

    1

    恕我直言,這是最好的方式,沒有必要改變任何東西。如果你不想動態附加/分離,你可以有一個現有img作爲佔位符,只是改變其src屬性,當你想改變它:

    <img id="placeholder" src="initial/path" /> 
    
    $("#placeholder").attr("src", result.message); 
    

    但既然你處理的圖像根據你的代碼建議,我認爲你的原始解決方案更適合你的情況。如果您決定刪除圖片或對列表或其他內容進行排序,您可以使用$("imageList img")進行選擇。

    編輯: OTOH如果你有一個非常複雜的結構,要在HTML的代碼也需要利用它的動態副本,您可以使用clone作爲一種替代方案:

    <div id="model" style="display:none">complex markup goes here</div> 
    
    $("#model").clone().attr("id",anotherID).appendTo(target).show(); 
    
    +0

    如果您克隆,則需要更改ID。 – epascarello 2012-03-11 13:42:41

    +0

    @epascarello感謝您指出這一點!答案已更新 – mgibsonbr 2012-03-11 14:01:56

    1

    使用一個模板。例如:

    <div style="display:none"> 
        <!-- This div contains all your templates --> 
        <img src="about:blank" class="classesYouNeed" id="uploadSuccess"> 
    </div> 
    

    ,然後用javascript:

    $("#ajaxUploadForm").ajaxForm({ 
        iframe: true, 
        dataType: "json", 
        ... 
        success: function (result) { 
        var img = $('#uploadSuccess') 
         .clone() 
         .attr('id', somethingElse) 
         .attr('src', result.message) 
    
        $("#imageList").prepend(img); 
        }) 
    }) 
    

    有jQuery的模板的框架存在,這將使這更簡單。

    2

    我不會有任何問題與......除非你是擔心無效的URL,它會破壞代碼...

    你可以使用簡單的JavaScript

    var img = new Image(); 
        img.src = result.message; 
    
    $("#imageList").prepend(img); 
    
    相關問題