使用replaceWith后,.click停止工作

lon*_*kie 2 html jquery html5 replacewith

好吧,我现在已经坚持了一段时间......

基本上我有两种方式我想要显示某个div.我计划使用replaceWith()替换#mainDiv与另一个版本的#mainDiv来创建一个函数.

这是功能:

function switchToChoice(){
            $('#myCanvas2').replaceWith('<div id="yesBox" width="150" height="90"><img id="yes" src="Yes-Button.png" width="110" height="55"></div><div id="noBox" width="150" height="90"><img id="no" class src="No-Button.png" width="110" height="55"></div>');

        }
Run Code Online (Sandbox Code Playgroud)

这可以工作并在调用时创建我想要的div框.div框中有两个图像,可以单击,但不执行单击操作.

这是在replaceWith之后无效的代码片段:

//If the user presses the Next button on the comment pages.
        $('#next').click(function() {
            $('#next').fadeTo(100, 0.25, function(){
                clearCanvas(ctx, c);
                wrapText(ctx, questionList[textPos], x, y-20, 275, 15);
                textPos++;
            });
            switchToChoice();
            $('#next').fadeTo(100, 1);
        });

        //If the user presses the Yes button on the question pages.
        $('#yes').click(function() {
            alert("boobs");
            $('#yes').fadeTo(100, 0.25, function(){
                clearCanvas(ctx, c);
                wrapText(ctx, questionList[textPos], x, y-20, 275, 15);
                textPos++;
            });
            $('#yes').fadeTo(100, 1);
        });

        //If the user presses the No button on the question pages.
        $('#no').click(function() {
            $('#no').fadeTo(100, 0.25, function(){
                clearCanvas(ctx, c);
                wrapText(ctx, questionList[textPos], x, y-20, 275, 15);
                textPos++;
            });
            $('#no').fadeTo(100, 1);
        });
Run Code Online (Sandbox Code Playgroud)

我的猜测是,当替换HTML时会丢失一些东西,但我真的不知道是什么.我对JQuery相当陌生并尽可能多地进行研究,但似乎我只是在圈子里.有人可以帮忙吗?

PSL*_*PSL 6

您正在创建动态的元素,则需要使用使用事件代表团.

您的事件将仅附加到当时DOM中存在的元素.因此,您需要通过将事件附加到文档或任何时间点存在的父元素来使用Delegated事件.你可以通过使用来做到这一点on()

     $(document).on('click', '#next', function() {
        $(this).fadeTo(100, 0.25, function(){
            clearCanvas(ctx, c);
            wrapText(ctx, questionList[textPos], x, y-20, 275, 15);
            textPos++;
        });
        switchToChoice();
        $(this).fadeTo(100, 1);
    });

    //If the user presses the Yes button on the question pages.
    $(document).on('click','#yes', function() {
        alert("boobs");
        $(this).fadeTo(100, 0.25, function(){
            clearCanvas(ctx, c);
            wrapText(ctx, questionList[textPos], x, y-20, 275, 15);
            textPos++;
        });
        $(this).fadeTo(100, 1);
    });

    //If the user presses the No button on the question pages.
     $(document).on('click','#no', function() {
        $(this).fadeTo(100, 0.25, function(){
            clearCanvas(ctx, c);
            wrapText(ctx, questionList[textPos], x, y-20, 275, 15);
            textPos++;
        });
        $(this).fadeTo(100, 1);
    });
Run Code Online (Sandbox Code Playgroud)