2012-04-04 251 views
-3

如何在表格內創建動態標籤。起初創建鏈接,然後裏面的鏈接創建一樣,如果我有一個img標籤..與jQuery動態創建img標籤?

<table> 
    <tr> 
     <td> 
      <a> 
       <img /> 
      </a> 

      // Add Some more when every time my function is run..? like that 
      // <a> 
      // <img/> 
      // </a> 

     </td> 
    </tr> 
</table> 

進出口使用這裏面的功能,但它沒有工作,幫助我。

$(document.createElement("img")).attr('Some attr'); 
+0

這很容易通過諮詢官方jQuery的文檔研究。 http://api.jquery.com/append/ – Patrick 2012-04-04 07:18:59

+1

不要忘了標記答案,如果你有你想要的信息 – 2012-04-04 07:52:30

回答

2

如果你指的JQuery通過 「jquree」 ,那麼試試這個:

$('table tr td').append('<a href="#"><img src="/favicon.ico"/></a>'); 
0
$(document).ready(function(){ 

    $('.any_element_you_want').html('<a href="/home" title="Home"><img src="image.png"></a>'); 

}); 
0

製作使用jQuery的比你中央社箱子圖像元素像下面

$(document).ready(function(){ 

    var elem = new Element('img', 
       { src: 'pic.jpg', alt: 'alternate text' }); 
    $(document).insert(elem); //here you can also make use of `append` method instead of this method 
} 

var img = new Image(1,1); ///params are optional 
img.src = ''pic.jpg'; 
+0

我試着這個,我認爲它的工作。 – QasimRamzan 2012-04-04 07:28:11

+0

@QasimRamzan - 如果符合您的要求,請接受並提出答案 – 2012-04-04 07:36:56

0
var td = $('table tr td'); 
td.append('<a><img src="whatever.jpg"/></a>'); 
2

好,我是不會回答這個問題,但我沒有看到任何正確的答案(從我的POV):

function addElement(tdId) { // Specify the id the of the TD as an argument 
    $('#' + tdId).append(// Append to the td you want 
     $('<a></a>').attr({ // Create an element and specify its attributes 
      'href': '/home', 
      'title': 'Home' 

     }).append(// Also append the image to the link 
      $('<img />').attr({ // Same, create the element and specify its attributes 
       'src': 'image.png', 
       'width': '100px', 
       'height': '100px' 
      }) 
     ) // Close the "append image" 
    ) // Close the "append anchor" 
} 

現在是一個純粹的jQuery的答案。一個JavaScript的答案將如下:

function addElement(tdId) { // Specify the id the of the TD as an argument 
    // Create the DOM elements 
    var a = document.createDocumentFragment('a'), 
     img = document.createDocumentFragment('img') // See the use of document fragments for performance 

    // Define the attributes of the anchor element 
    a.href = '/home' 
    a.title = 'Home' 

    // Define the attributes of the img element 
    img.src = 'image.png' 
    img.width = '100px' 
    img.height = '100px' 

    // Append the image to the anchor and the anchor to the td 
    document.getElementById(tdId).appendChild(a.appendChild(img)) 
} 

我認爲js版本更具可讀性。但這只是我的看法; o)。

0

在每次點擊按鈕,它會添加img標籤與圖像url abc.png 並添加到具有id imagediv的div。

$("button").click(function() 
{ 
    var img=$('<img id="dynamic">');  
    $(document.createElement('img')); 
    img.attr('src',"abc.png"); 
    img.appendTo('#imagediv'); 
    });