克隆输入字段上的.keyup()

时间:2014-12-04 23:31:56

标签: javascript jquery html clone keyup

我克隆了输入字段,然后当我编辑克隆的输入字段时,我试图将新值作为文本字符串放入外部div中。感谢您的帮助!

function cloneClue(target){
    clueCount++;
    var myClueField = $(target).prev().find('#textClue');
    var myClone = myClueField.clone().attr('id','textClue' + clueCount);
    var clueName = myClone.find('.clueName');
    var clueContent = myClone.find('.clueContent');
    var clueRemove = myClone.find('.clueRemove'); 
    var clueNamePreview = myClone.find('.clueNamePreview');
    var clueContentPreview = myClone.find('.clueContentPreview');

    clueName.attr('name', "clueName" + clueCount);
    clueName.attr('id', "clueName" + clueCount);
    clueContent.attr('name', "clueContent" + clueCount);
    clueContent.attr('id', "clueContent" + clueCount);
    clueRemove.attr('id', "clueRemove" + clueCount)

    clueNamePreview.attr('id', "clueNamePreview" + clueCount);
    clueContentPreview.attr('id', "clueContentPreview" + clueCount);

    clueRemove.click(function() {
        $(this).parent().remove();
    });
    $('#clueField').append(myClone);
    myClone.show();
}
var clueCount = 0;

$(document).ready(function() {  

    $("#addTextClue").click(function(){
        cloneClue(this)
    });

    $('.clueName').keyup(function(){
        var nameVal = $(this).val();
        $(this).parent().find('.clueNamePreview').html(nameVal);
    });

    $('.clueContent').keyup(function(){
        var contentVal = $(this).val();
        $(this).parent().find('.clueContentPreview').html(contentVal);
    });

});

这里是jsfiddle

2 个答案:

答案 0 :(得分:2)

您需要将.on用于动态添加到DOM的任何元素。

将您的jQuery更改为:

$(document).on("keyup", ".clueName", function() {
    ....
}

等...

答案 1 :(得分:1)

您的问题是您在document.ready函数中定义了键控侦听器。此时,您的克隆元素不在您的DOM中,因此没有任何监听器附加到您的克隆。只需在添加输入克隆之后立即移动这部分代码:

http://jsfiddle.net/8yv5x7dg/2/