0

似乎我遇到了一些问题,我很困惑为什么......

编码:

$(".post-click").click(function()
{
    var classid = $(this).attr('id');
    var postid = $(this).attr('id');
    postid = postid.replace('post-click-id_', '');

    alert("ID: " + classid + " PostID: " + postid);

    $(this).replaceWith('<img SRC="assets/img/refresh.gif" ALT="" id="' + classid + '">');

    $.post("likepost.php", { postid: postid } , function(data)
    {
        $(document).foundationTooltips();

        alert(data);
            $("#" + classid).replaceWith(data);

            var classes = $("#" + classid).attr('class');

            alert(classes);
    });
});

现在,这是做什么的,当您单击它时,它会替换您单击的 ID 的文本。现在,最重要的是我得到了这个:

$(".post-click").click(function()
{

替换后似乎不再调用 post-click。为了确保我用好的类代替了它,我把'var classes = ...'放在那里。它提醒点击后类在替换中。

替换为:<a class="post-click" href="#" >test</a >";

任何想法为什么 jQuery 不再调用后点击?

4

1 回答 1

2

When using replaceWith, you are replacing the DOM element, complete with its event bindings.

Luckily, jQuery provides .on which allows you to use event delegation (as opposed to looping through the new content rebinding your events).

You apply it to a parent node of post-click and then specify the class in the arguments.

e.g.

$(".some-parent-elem").on("click", ".post-click", 
       function (){...do stuff on click...});

How this works is that it listens for clicks on .some-parent-elem (which due to event bubbling will mean it fires when you click on a child of that element) and then if the original target element that was clicked has the class of post-click, it runs the function.

于 2012-10-23T10:01:35.510 回答