1

我使用 JQuery 将 HTML 代码插入网页

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

查询:

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 回答