2016-10-22 102 views
0

我已經看到了SO this example附加元素追加多個元素的HTML

jQuery('<div/>', { 
    id: 'foo', 
    href: 'http://google.com', 
    title: 'Become a Googler', 
    rel: 'external', 
    text: 'Go to Google!' 
}).appendTo('#mySelector'); 

,但我試圖創建這種結構

<ul id="list"> 
    <li> 
    <a> 
     <img src="source_example" /> 
    </a> 
    </li> 
</ul> 

UI元素將已經存在,所以我我正打算創建新的LI,A和IMG元素。

現在我做這個

li = $("<li />"); 

a = $("<a />"); 
a.href = "href"; 
a.id = "pic"; 

img = $("<img />"); 
img.id = "id"; 
img.src = "src"; 
img.width = "100"; 
img.height = "100"; 

a.append(img); 
li.append(a); 
$("#list").append(li); 

但它只是附加一個空裏到#list UL。它沒有顯示img或定位標記。我會用SO上述方法,也乾淨,但我沒有對每個鋰ID屬性也沒有我真的很想ID添加到每個L1

+0

似乎做工精細,無論是李和圖像是有 - > https://jsfiddle.net/adeneo/rxy7u4w2/ – adeneo

+0

哦嗯,我猜像src和HREF屬性沒有出現 – abcf

+1

嗯,不,那是因爲你已經在jQuery對象上創建了屬性。 jQuery使用'img.attr('src','someimage.png')'設置屬性 – adeneo

回答

1

在你需要創建你的新元素之前,你可以將它附加到你的DOM元素之後。

爲了創建您的結構,你需要:

  1. 創建UL節點
  2. 追加到此節點的節點李
  3. 追加到李節點錨節點
  4. ...最後形象

這個新元素現在可以追加到您的元素:

$('<ul/>', {id: 'list'}) 
 
    .append($('<li/>') 
 
     .append($('<a/>') 
 
      .append($('<img/>', {src: 'source_example'})) 
 
)).appendTo('#mySelector'); 
 

 

 
// 
 
// debug print 
 
// 
 
var tabs = 0; 
 
console.log(document.querySelectorAll('#mySelector ul')[0].outerHTML.replace(/><./g, function(match) { 
 
    if (match[2] == '/') { 
 
    tabs -= 3 
 
    } else { 
 
    tabs += 3 
 
    } 
 
    return '>\n' + ' '.repeat(tabs) + match.substr(1); 
 
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<div id="mySelector"> 
 
    <p>This is my element</p> 
 

 
</div>

+1

完美,謝謝 – abcf

0

你可以試試這個方法也

var li = '<ul id="list">'+ 
      '<li>'+ 
      '<a href="">'+ 
       '<img src="source_example" />'+ 
      '</a>'+ 
     '</li>'+ 
     '</ul>'; 
$("#list").append(li);