1

JQueryを使用してHTMLコードをWebページに挿入しています

<div class="title-OthProb-outer">    
        <input type="button" class="title-add-non-standard-issue" value="Add a Non Standard Problem" />
</div>

Jクエリ:

var titleString = '<div class="title-OthProb-wrap title-nonStand1"><h3>Non Standard   Problems</h3><!-- redacted for readability! --></div><input type="button" class="title-add-another" value="+" /><br>';

$('div[class^=title-OthProb-wrap]').hide();
$('input[class^=title-add-another]').hide();
$(function() {
    $('.title-add-non-standard-issue').on('click', function() {
    $('input[class^=title-add-non-standard-issue]').hide();
       var that = this;
       var elem = $(that).closest('.title-OthProb-outer').append(titleString);
       var elem = $(that).closest('.title-OthProb-outer').find('.title-OthProb-wrap');
       $(elem).fadeIn(500);
});

これは正常に機能しますが、html を複製する機能が必要です。html がすべてページにあるとき、つまり Jquery によって生成されていないときに機能しましたが、「title-add-another」ボタンをクリックしても何もしません。

$(function() {
$('.title-add-another').click(function() {
    // Add non-standard problems
    var num     = $('.title-OthProb-wrap').length; // how many "duplicatable"  fields we currently have
    var newNum  = new Number(num + 1);      // the numeric ID of the new input field being added

    // create the new element via clone(), and manipulate it's ID using newNum value
    var newElem = $('.title-nonStand' + num).clone().attr('class', 'title-OthProb-wrap title-nonStand' + newNum);

    // insert the new element after the last "duplicatable" input field
    $('.title-nonStand' + num).after(newElem);         
    });
});

それをコンソールに入力すると、ボタンが機能します...ページがロードされるまで存在しない要素をJqueryはどのように処理しますか?

4

1 に答える 1

2

委任を使用する必要があります...

$(function () {
    $(document).on('click','.title-add-another',function () {
        // Add non-standard problems
        var num = $('.title-OthProb-wrap').length; // how many "duplicatable"  fields we currently have
        var newNum = new Number(num + 1); // the numeric ID of the new input field being added

        // create the new element via clone(), and manipulate it's ID using newNum value
        var newElem = $('.title-nonStand' + num).clone().attr('class', 'title-OthProb-wrap title-nonStand' + newNum);

        // insert the new element after the last "duplicatable" input field
        $('.title-nonStand' + num).after(newElem);
    });
});
于 2013-06-21T13:14:20.970 に答える