2016-10-22 97 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);