追加

时间:2017-03-29 14:54:25

标签: javascript jquery html append

我想动态点击段落的第一次点击,但它不起作用。



$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>';
    $('body').append(append_code);
    $(".hrefclick").click();

    $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p>
&#13;
&#13;
&#13;

js Fiddle

3 个答案:

答案 0 :(得分:2)

您需要在委派后触发click(),只需更改行的顺序:

$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>';
    $('body').append(append_code);

    $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
    $(".hrefclick").click();
    
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p>

答案 1 :(得分:0)

$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>';
    $('body').append(append_code);
    $(".hrefclick").click();

    $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
    $('.hrefclick').trigger('click');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p>

答案 2 :(得分:0)

除了一件事之外,你所做的一切都是正确的 - 你在点击本身后声明第二次点击的事件处理程序。因此,当第二次点击被触发时,您还没有声明处理程序,并且您没有看到任何警报。 我在下面重新安排了它。尝试运行以下代码段。

&#13;
&#13;
$(document).ready(function() {
  $(".newclass").click(function() {
    var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>';
    $('body').append(append_code);
      
      //on click event handler should be declared first before clicking
     $(document).on('click', '.hrefclick', function(e) {
      alert("yess! You're clicked");
      // do whatever
    });
    
    $(".hrefclick").click();

   
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="newclass">
  Hit me!
</p>
&#13;
&#13;
&#13;