jQuery:将追加函数绑定到新附加的div

时间:2017-09-14 16:03:07

标签: jquery

在网页中,div中包含多个帖子,其中包含班级名称' postContainer'。下面的代码会为每个div添加一个按钮。

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

我的代码最初有效,但是当ajax显示新帖子时,它的div没有按钮

2 个答案:

答案 0 :(得分: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 :(得分:-1)

尝试这样做:https://jsfiddle.net/ff2v0q6v/1/

&#13;
&#13;
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
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;