【问题标题】:Jquery can't use clone on appended htmlJquery 不能在附加的 html 上使用克隆
【发布时间】:2013-06-18 15:15:23
【问题描述】:

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

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

jquery:

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 如何处理在页面加载之前不存在的元素?

【问题讨论】:

  • 代表团,一个美妙的词(世界)
  • 是我遗漏了什么还是你想克隆一个不存在的元素?
  • @scunliffe 哦,看来你是对的
  • 检查页面事件处理程序表明,添加另一个按钮后没有设置任何内容。我会调查委托。
  • 所以这个元素$('.title-nonStand' + num) 在你尝试克隆它时已经存在,对吧?

标签: jquery append clone


【解决方案1】:

您需要使用委托...

$(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);
    });
});

【讨论】:

  • 但你不应该使用文档,而是使用'.title-add-another'元素的最接近的静态容器,这样会更好
  • OK 就可以了。感谢您的帮助。
猜你喜欢
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-20
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多