将李添加到另一个李

时间:2014-05-08 06:27:19

标签: jquery append html-lists

我有一个带有userid attr的无序列表(即uid)。

<li uid="1">KEY A</li>
<li uid="2">KEY B</li>
<li uid="3">KEY C</li>
<li uid="4">KEY D</li>
<li uid="5">KEY E</li>
<li uid="6">KEY F</li>

我使用jQuery使用uid获取$(this).attr('uid')并将其传递给将查找id并返回值的页面。我用来发送数据的代码如下。

<script>
$(document).ready(function(){
  $("li").click(function(){
  var val = $(this).attr("uid");
$.post("tree-process.php",{val:val},function(response){
    alert(response);
    });
  });
});
</script>

此响应值将如下所示ul

<ul>
  <li uid="1">VAL A</li>
  <li uid="2">VAL B</li>
</ul>

我需要将ul响应插入点击的li内,如下所示:

<li uid="1">KEY A</li>
  <ul>
    <li uid="1">VAL A</li>
    <li uid="2">VAL B</li>
  </ul>
</li>

如何将响应值附加到li?

谢谢!!

1 个答案:

答案 0 :(得分:0)

$("li").click(function() {
   var uid =  $(this).attr('uid');
    // pass the uid to the next page and get the response
    var response = functionName(uid);// some function call back to get the <ul> corresponding to that li uid

   // Now add the response which is a ul to the li

     if($(this).find('ul').length===0) {
      $(this).append(response); 
    }
   // insert your response there
});

根据您的代码

$(document).ready(function(){
  $("li").click(function(){
  var self = this;
  var val = $(this).attr("uid");
   $.post("tree-process.php",{val:val},function(response){
       if($(self).find('ul').length===0) {
          $(self).append(response);
        }
    });
  });
});

<强> JSBIN Sample