jquery。删除不工作

时间:2011-01-27 07:46:56

标签: jquery hyperlink

我试图添加到div上的超链接onClick和我打算当我再次碰撞时,附加的超链接被删除...一切正常工作点击超链接附加到目标div但它们没有被删除。 ..

<script type="text/javascript">
    $(document).ready(function() {

        $("[href=#]").click(function() {
            if ($("#appendContainer").is(":parent")) {
                var child = $("#appendContainer").children().attr("id");
                alert(child);
                $('#' + child).remove();

            }

            $("#appendContainer").append(
$("<a/>", { href: "#", id: "helloWorldLink" }).text("Helloworld"));
        });
    });

</script>




    <a href="#">click here</a>
         <div id="appendContainer"></div>

3 个答案:

答案 0 :(得分:1)

您总是附加锚链接,但如果已经存在则将其删除。你需要在if之后添加else块。即:

<script type="text/javascript">
    $(document).ready(function() {
        $("[href=#]").click(function() {
            if ($("#appendContainer").is(":parent")) {
                var child = $("#appendContainer").children().attr("id");
                alert(child);
                $('#' + child).remove();

            }
           else {
            $("#appendContainer").append($("<a/>", { href: "#", id: "helloWorldLink" }).text("Helloworld"));
          }
        });
    });  </script>

答案 1 :(得分:1)


$(function() {
  function linkClickHandler() {
    var appendContainer = $('#appendContainer');
    appendContainer.children().remove();
    appendContainer.append(
       $('<a/>', {
          href: '#',
          id: 'helloWorldLink',
          click: linkClickHandler,
          text: 'HelloWorld'
       })
    );

    $('[href=#]').click(linkClickHandler);
  }
}

或使用live(但在这种情况下速度较慢)。

答案 2 :(得分:0)

您添加的链接没有您的onClick侦听器。

尝试使用.live()来设置事件处理程序。使用此代码:

$(document).ready(function() {
        $("[href=#]").live('click', function() {
            if ($("#appendContainer").is(":parent")) {
                var child = $("#appendContainer").children().attr("id");
                alert(child);
                $('#' + child).detach();
                return;
            }

            $("#appendContainer").append(
              $("<a/>", { href: "#", id: "helloWorldLink" }).text("Helloworld")
            );
        });
});

请注意,我在return之后添加了detach(),以避免在删除旧链接后添加新链接。

相关问题