2017-09-14 114 views
-1

在網頁中,div中包含的帖子數量與類名稱爲「postContainer」。下面的代碼將爲每個div添加一個按鈕。jQuery:將附加函數綁定到新添加的div

$('.postContainer').find('.fileText') 
     .append('<button class="exbutton d1" type="button">postname</button>'); 

我的代碼工作開始,但作爲一個新的帖子出現由ajax,它的DIV沒有按鈕

+0

您可以使用jsfiddle或代碼片段ol更好地解釋問題? –

+0

'.find()'只是查找當前存在的元素。除非您在事件處理程序中運行它,否則將來無法自動實現此功能。 – Barmar

+1

你能澄清這個問題嗎? –

回答

-1

嘗試做這樣:https://jsfiddle.net/ff2v0q6v/1/

var AJAXcontent = "Lorem <b>ipsum</b> dolor sit amet..."; // The AJAX post HTML 
 

 
// OK. now... 
 

 
var $exbutton = $("<button/>", { 
 
    "class": "exbutton d1", 
 
    type: "button", 
 
    text: "postname" 
 
}); 
 

 

 
$("<div/>", { 
 
    "class": "postContainer", 
 
    html: AJAXcontent, // 1. Insert the post content 
 
    append: $exbutton, // 2. append the button 
 
    appendTo: "body"  // 3. append the DIV wherever you want 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0
$(document).ajaxComplete(function() { 
$("body").find('.postContainer').each(function(){ 
    var $this = $(this); 
    if($this.find('.exbutton').length === 0) { 
     $this.append('<button class="exbutton d1" type="button">postname</button>'); 
    } 
    }); 
}); 
+1

歡迎來到Stack Overflow!儘管這段代碼可以解決這個問題,但[包括一個解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高您的帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要用解釋性註釋來擠佔代碼,這會降低代碼和解釋的可讀性! – Machavity