简体   繁体   English

动态添加事件监听器

[英]adding event listener dynamically

I'm trying to do add an event listener to a dynamically created object 我正在尝试向动态创建的对象添加事件侦听器

var teamDiv = document.createElement("div");

obviously, following doesn't work: 显然,以下操作无效:

teamDiv.onDragStart="drag(event)";

so I tried this: 所以我尝试了这个:

teamDiv.addEventListener("dragstart",function(event){drag(event);});

and

var dragFunction = new Function("event","drag(event);");
teamDiv.addEventListener("dragstart", dragFunction);

and

teamDiv.addEventListener("dragstart", function(teamDiv) {dragObj(teamDiv);});

but nothing works. 但没有任何效果。 Can anyone help me with this? 谁能帮我这个?

thanks in advance, 提前致谢,

Dirk 短剑

Did you remember to a) append the element and b) make it draggable? 您还记得a)追加元素和b)使元素可拖动吗? See this: 看到这个:

var teamDiv = document.createElement('div');

// make it draggable
teamDiv.draggable = 'true';

// append it
document.body.appendChild(teamDiv);

function drag(event) {
    alert("You dragged me");
}

// either one of those will work
// teamDiv.addEventListener("dragstart", drag);
// teamDiv.ondragstart = drag;

Fiddle: http://jsfiddle.net/ZfXa5/1/ 小提琴: http : //jsfiddle.net/ZfXa5/1/

Events aren't camel-cased, so onDragStart won't work, it has to be ondragstart . 事件不是驼峰式的,所以onDragStart将不起作用,它必须是ondragstart You should also really avoid putting executable code into strings. 你也真的应该避免将可执行代码转换为字符串。 They will be eval -ed, which is just completely unnecessary. 将对它们进行eval ,这完全没有必要。 eval is evil. eval是邪恶的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM