创建新元素时创建jQuery

3

我正在寻找一种方法,在创建新元素时可以创建jQuery脚本。

以下是我所做的:

<div id = "content">
content
</div>

<script>
$('#content').click(function(event) {
  $('#content').append('<div id='+ Math.floor((Math.random() * 100) + 1) +'> 123 </div>');
});

// dynamically create click function? 
$('#randomNumber').click(function(event) {
    console.log("Random id");
});
</script>
3个回答

2
您不需要这样做,因为您可以使用.on()来应用于您当前和未来的元素,就像这样:
$("#content").on("click", "div", function() {
    console.log(this.id);
});

这实际上为所有存在或尚不存在于`#content`内部的`
`元素创建了一个`click`事件处理程序,该处理程序记录了`this`的`id`。
而您的其他处理程序则是...
$('#content').click(function(event) {
  $('#content').append('<div id='+ Math.floor((Math.random() * 100) + 1) +'> 123 </div>');
});

创建这样的
。只需确保不要重复使用id,因为这会导致无效的HTML,对于SEO评分来说是受惩罚的。

这太棒了!我正在寻找这种方法! - rj487
@CodaChang,我很高兴我能帮到你。 - Lajos Arpad

1
尝试:
$('#content').click(function(event) {
  var randDiv = $('<div id='+ Math.floor((Math.random() * 100) + 1) +'> 123 </div>').appendTo('#content');
  // dynamically create click function? 
  randDiv.click(function(event) {
    console.log("Random id");
  });
});

0
你需要创建一个函数来生成一个类似于这样的随机数:
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

当您附加一个具有随机ID的新div时,请使用它。

编辑:这里是一个jsbin https://jsbin.com/cimusoxale/edit?html,js,console,output


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接