2011-06-17 77 views
24

我想在元素創建完成後調用一個函數。有沒有辦法做到這一點?如何在jquery中創建元素後調用函數?

例子:

$("#myElement").ready(function() { 
    // call the function after the element has been loaded here 
    console.log("I have been loaded!"); 
}); 
+0

有什麼背景? – 2011-06-17 13:04:48

+0

我不知道,我是在WYSIWYG編輯器裏寫的。我寫這篇文章是爲了讓人們看到我期望的成就。 – 2011-06-17 13:05:22

+1

當你的意思是創建,你的意思是追加到DOM? – Tomgrohl 2011-06-17 13:05:48

回答

35

你如何創建元素之後?

如果您使用靜態HTML創建它,那麼只需使用.ready(handler).on("load", handler)。如果你使用的是AJAX,雖然這是另一個魚的水壺。

如果你使用jQuery的load()功能再有就是你可以運行一個回調時被加載的內容:

$('#element').load('sompage.html', function(){ /* callback */ }); 

如果你使用jQuery的$.ajax$.get/$.post功能,然後有一個成功的回調即:

$.ajax({ 
    url: 'somepage.html', 
    success: function(){ 
    //callback 
    } 
}); 

如果你剛剛創建的元素並將其附加這樣的:

$('body').append('<div></div>'); 

然後你就可以做到這一點,而不是:

$('<div />', { id: 'mydiv' }).appendTo('body').ready(function(){ /* callback */ }); 

但這並不重要 - 因爲它是同步的(這意味着下一行代碼將不會運行,直到它添加的元素到DOM反正... - 除非你加載圖像和這樣),所以你可以這樣做:

$('<div />', { id: 'mydiv' }).appendTo('body'); 
$('#mydiv').css({backgroundColor:'red'}); 

但acctually,說,你可能只是這樣做:

$('<div />', {id:'mydiv'}).appendTo('body').css({backgroundColor:'red'}); 
7

你可能想看看jQuery的live事件。您將事件處理程序附加到選擇器,該選擇器現在或者在DOM中創建其他元素之後匹配。

所以,如果你有一個<ul>和動態創建新<li>項目,在你的$(document).ready()你就可以將一個選擇將事件處理程序,以便所有<li>元素將有線爲該事件。

這是jsFiddle示例演示live

希望這會有所幫助。

-1

最直接的就是直接調用回調創建該元素:)

1

結賬。生活()創建的元素之後最好,,

$('.clickme').live('click', function() { 
     // Live handler called. 
    }); 

    And then later add a new element: 

    $('body').append('<div class="clickme">Another target</div>'); 
0
$("<div id=\"elem\"></div>").appendTo("#parent").each(function(){ 

    console.log("I have been created!"); 

}); 
1

你可以試試這個代碼

$('body').on('click', '#btn', function() { 
 
    $($('<div>').text('NewDive').appendTo("#old")).fadeOut(0).fadeIn(1000); 
 
})
#old > div{ 
 
    width: 100px; 
 
    background: red; 
 
    color: white; 
 
    height: 20px; 
 
    font: 12px; 
 
    padding-left: 4px; 
 
    line-height: 20px; 
 
    margin: 3px; 
 
}
<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
    <meta charset="utf-8"> 
 
    <title>Test</title> 
 
    <link rel="stylesheet" href="./index.css"> 
 
    </head> 
 
    <body> 
 
    <div> 
 
     <!-- Button trigger modal --> 
 
     <button type="button" id="btn">Create Div</button> 
 
     <div id="old"> 
 

 
     </div> 
 
    </div> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    </body> 
 
</html>

1

有時這是需要創建/加載的DOM元素在您自己的腳本之外,或者通過不同的js庫或您的直接控制之外的事件。

對於這樣的場景,我總是設置一個時間間隔,它定期檢查目標元素是否存在,如果這是真的,則間隔刪除自身並運行回調函數。

對於這一點,我有一個預定義的功能,我重用:

function runAfterElementExists(jquery_selector,callback){ 
    var checker = window.setInterval(function() { 
    //if one or more elements have been yielded by jquery 
    //using this selector 
    if ($(jquery_selector).length) { 

     //stop checking for the existence of this element 
     clearInterval(checker); 

     //call the passed in function via the parameter above 
     callback(); 
     }}, 200); //I usually check 5 times per second 
} 

//this is an example place in your code where you would like to 
//start checking whether the target element exists 
//I have used a class below, but you can use any jQuery selector 
runAfterElementExists(".targetElementClass", function() { 
    //any code here will run after the element is found to exist 
    //and the interval has been deleted 
    });