jquery
  • append
  • clone
  • 2013-06-21 49 views 1 likes 
    1
    使用jQuery插入HTML代碼到網頁

    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的處理元素不存在的頁面加載後,直到?

    +1

    代表團,一個美好的字(世界) –

    +0

    我思念的東西或者是你想克隆一個不存在的元素? – scunliffe

    +1

    @scunliffe哦,看起來你是對的 –

    回答

    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); 
        }); 
    }); 
    
    +0

    嘿,多數民衆贊成在死靈活,這是行不通的:)乾杯 – Funk247

    +0

    但你不應該使用文件,而是最接近的'.title-add-another'元素的靜態容器,這是更好的 –

    +0

    好的。謝謝您的幫助。歡迎您致電 – Funk247

    相關問題