jQuery - `on` 事件在 jQuery.replaceWith 之后不起作用 [英] jQuery - `on` event doesn't work after jQuery.replaceWith

查看:32
本文介绍了jQuery - `on` 事件在 jQuery.replaceWith 之后不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要这样的链接:单击时变为文本,鼠标移出文本时返回链接.

I want a link like this: When it's clicked, it changes to text, when mouse out of the text, it returns to link.

HTML:

    <a href="#">click me and change to text</a>

JS:

    $("a").on('click',function(){
        var $lnk = $(this);
        var $replace = $('<span>');
        $replace.text($lnk.text());
        // Link to Text
        $lnk.replaceWith($replace);
        // Text to Link
        $replace.one('mouseout',function(){
            $replace.replaceWith($lnk);
        });
        return false;
    });

该代码仅在第一次有效.似乎 $("a").on("click",function(){})replaceWith 后不起作用.

The code only works first time. Seems that $("a").on("click",function(){}) not working after replaceWith.

小提琴:http://jsfiddle.net/uABC9/4/

我使用 jQuery 1.10.1 并测试了 FF 和 Chrome.请帮忙.

I am using jQuery 1.10.1 and tested both FF and Chrome. Please help.

推荐答案

替换

$("a").on('click',function(){

$(document).on('click','a',function(){

所以你可以使用委托事件.这样做,您的处理程序将适用于未来可以创建的锚元素,这是您需要考虑到在执行 replaceWith

so you can use delegated events. Doing so, your handler will apply for future anchor elements that could be created and this is what you need taking into account that you're removing the anchor from document when executing replaceWith

演示

有关委托事件的更多详细信息此处(查看直接和委托事件"部分)

More details about delegated events here (check section "Direct and delegated events")

这篇关于jQuery - `on` 事件在 jQuery.replaceWith 之后不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆