0

我有一个<li>里面有 JQuery 代码的项目。我想克隆它<li>$.getJSON url在 cloned 内部进行更改<li>。是否可以?

这里的代码:

<ul class="exercise2">2:2 Exercise - 1

            <li class="exset327" id="exset327"><var class="exset">327</var>:Сет - <var class="setnum">1</var>
              <a class="DelSet" href="#">[-]</a>
              <script>
                $(".exset327 a").click(function () {
                  $.get("/workouts/del_set/327/"); // Here I want to change '327' in cloned item to some variable then clone
                  $(this).parent().remove();
                  $(".exercise2 li").each(function(){
                    $(".setnum",this).html($(this).index() + 1);
                  });
                  return false;
                });
              </script>
            </li>

        <a class="AddSet" href="#">Add set</a>   // link which make a clone of above <li>
        <script>
          $(".exercise2 a.AddSet").click(function () {
            $.getJSON("/workouts/add_set/2/", function (json) {
              //alert(json.newsetnum);
              var newsetid = json.newsetid;         // returnet from server
              var newsetnum = json.newsetnum;       // returned from server
            // clone
            var clonedLi = $(".exercise2 li:last").clone(true); // 'true' to clone with event handler
            // change attributes
            $(clonedLi).attr("id", "exset" + newsetid);
            $(clonedLi).attr("class", "exset" + newsetid);
            // change content
            $(clonedLi).find(".exset").html(newsetid);
            $(clonedLi).find(".setnum").html(newsetnum);
            // add
            $(clonedLi).insertAfter(".exercise2 li:last");
            });
          });
        </script>
</ul>

如果我在克隆URL时单击(删除)链接时不会更改,则删除以前的链接。[-]<li>

4

1 回答 1

0

我会用另一种方法回答你,因为你的做法似乎不是最优的。克隆 DOM 元素很好,但克隆标签并不是很优雅。

似乎您正在执行相同的操作,但使用不同的元素或变量。有一种很好的方法可以使用泛型类进行此类工作 - 并使用 .data() 使它们更精确;

的HTML

<li class="exset327" id="exset327">
  <var class="exset">327</var>:Сет - <var class="setnum">1</var>
  <a class="DelSet" href="#" data-exset="327" >[-]</a>
</li>

和 JS:

$(document).on("click", ".DelSet", function() {
    var exset = $(this).data("exset");

    $.get("/workouts/del_set/"+exset+"/"); 
    $(this).parent().remove();
    $(".exercise2 li").each(function(){
      $(".setnum",this).html($(this).index() + 1);
    });
    return false;
 });

这部分 javascript 将确保每个新的“.DelSet”都有一个点击监听器,并执行下面的代码。

因此,您所要做的就是克隆 <li> 并修改 data-exset。

$(clonedLi).find(".DelSet").data("exset", netsetid);
于 2012-10-24T14:37:14.403 回答