单击动态按钮上的功能,实时/不工作

问题描述 投票:0回答:2

我试图在单击动态生成的按钮时运行一个函数。它出于某些原因似乎不起作用,无论我尝试使用什么方法。

JavaScript的

//Generating the button
$('<div><h3>Back<h3></div>')
  .attr('class', 'rtext btn arrowback').attr('role', 'button').attr('id', '2')
  .appendTo($(".row1")).hide().delay(800).fadeIn(1000);

//function when button is clicked
$(".row1").on("click", ".arrowback", function(){
    var userID = this.id;
    alert(userID);
});

我尝试过使用.on,我尝试使用.live:

$(".arrowback").live("click", function(){
   var userID = this.id;
   alert(userID);
});

但似乎没有任何效果。我的语法不正确吗?

javascript jquery function button dynamic
2个回答
0
投票

啊,我现在已经解决了它,如果动态生成父和子,下面的函数将起作用:

$(document.body).on("click", ".arrowback", function(){
    var userID = this.id;
    alert(userID);     
});

0
投票

动态生成元素还允许将事件绑定到最近创建的元素。

看看这个codepen:http://codepen.io/andtankian/pen/dXpZPR

$('div').append("<div></div>");
$('div>div').addClass("row1");

//Generating the button
$('<div><h3>Back<h3></div>')
  .attr('class', 'rtext btn arrowback').attr('role', 'button').attr('id', '2')
  .appendTo($(".row1")).hide().delay(800).fadeIn(1000);

//function when button is clicked
$(".row1").on("click", ".arrowback", function(){
    var userID = this.id;
    alert(userID);
});

我模拟了你的环境,一切正常。

© www.soinside.com 2019 - 2024. All rights reserved.