我有一个 AgentClass,其方法为 this.move。它使用静态对象,但是当我通过 .append() 创建新的 HTML 对象时,我无法将它们与我的 this.move 方法一起使用。
所有新对象都有一个 ID,我想使用 move 方法为它们设置动画。
我经常读到“live, on, ...”,但他们都需要一个事件...我没有这样的事件。他们直接移动。我尝试过类似的事情:
$('.agents').on("load", Agent.move());
但这不起作用...有什么想法吗?
代码:
var Agent = function(agentType, xTarget, yTarget) {
...
this.move = function() {
var id = this.agentId;
$('.agent#'+id).animate({
left:"200px"
}, 1000);
}
}
我将它们 append 在这之后,如下所示:
for (deployed = 0; deployed <= agents; deployed++) {
$('.agents').append('<div class="agent" id="'+deployed+'"></div>');
}
如果有人能帮助我那就太好了!?
最佳答案
You can use .clone(true) A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false.
var agents = 6;
for (deployed = 0; deployed <= agents; deployed++) {
$element = $('<div class="agent" id="'+deployed+'"></div>').clone(true);
$('.agents').append($element);
}
.agent {
height:50px;
width:50px;
background-color:yellow;
margin-bottom:10px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Agent</title>
</head>
<body>
<div class="agents">
</div>
</body>
</html>
但是为了最大程度地优化事件,最好使用事件处理程序“on”来监视重新加载 DOM 后将添加的项目。 这会分配更少的内存
关于javascript - append 元素上的绑定(bind)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37622788/