为什么当事件变为“true”时,我的 JQuery 函数没有在克隆的元素上触发

Why is my JQuery function not triggered on a cloned element when the event becomes "true"?

本文关键字:元素 函数 JQuery 事件 true 我的 为什么      更新时间:2023-09-26

我一直在制作这个表单,必须使后端用户能够创建新问题供用户回答。在第一个 .on(click) 事件之后,表单将成功克隆并追加到div(选择器 #content),但如果按下克隆的按钮,它不会再次复制表单。应用于我的下拉选择的 .on(change) 事件确实像它应该的那样更改了相应div 的内容,但仅限于原始表单。

这是 JQuery 代码:

$(document).ready(function () {
$('.addAnswer').on("click", function () {
    var idx = $('#mp div[name^="antwoord"]:last').index() + 1;
    $clone = $('#mp div[name^="antwoord"]:first').clone(true, true).attr('class', 'answer content_' + idx);
    $('.removeAnswer').show;
    $('#mp').append($clone);
    $('.answer:last').each(function () {
        $('b:last').empty();
        $('b:last').prepend(String.fromCharCode(64 + idx) + ". ")
        $('.addAnswer').on("click", function () {
            idx++;
        });
    });
    if (idx == 2) {
        $('.removeAnswer').show();
    }
});
$('.nextq').click(function () {
    var newqid = $('#content form:last').index() + 1;
    $('.done, .nextq, .remove').hide();
    $('#content').append('<hr>');
    $('#content').append($('form').html()).attr('class', 'q_' + newqid);
    $('.nextq').on("click", function () {
        newqid++;
    });
    $('.done:last, .nextq:last, .remove:last').show();
    return false;
});
$('.group').hide();
$('#text:last').show();
$('.select:last').on("change", function () {
    $('.group').hide();
    $('#' + $(this).val() + ':last').fadeIn();
    $('button.' + $(this).val() + ':last').fadeIn();
});
});

因为我认为发布整个HTML模板有点太多了,所以我为你们提供了一个JSFiddle。

对于那些感觉善良的人来说,还有一个额外的问题:在 JQuery 代码中,可以看到 HTML 的内容正在使用 .html() 进行解析并附加 .append。(JSFiddle 上的第 33 行)当 .on(change) 函数切换它应该更改的分区内容时,.html() 会看到这些更改并随之而来。我希望 .on(click) 函数将div 的内容附加到其原始状态,由后端用户事先进行的更改保持不变。对此的任何帮助都将是非常有义务的。

为了让 jQuery 触发新元素,你可以做类似的事情

$( document ).on( "click", "<your id or class>", function() {
  //Do stuff
});