简体   繁体   English

如何将事件附加到字符串形式的标签上?

[英]How can I attach event to a tag which is in string form?

I'm creating html on runtime like this: 我在运行时这样创建html:

var myVar = "<div id='abc'>some clickable text</div>"

Now, I want to attach some event, say onclick, to this div. 现在,我想向该div附加一些事件,例如onclick。 How can I do that on next line? 我如何在下一行上做到这一点? I'll add this to DOM later. 稍后将其添加到DOM。

PS: I've to accomplish this without using JQuery. PS:我必须不使用JQuery来完成此操作。

Instead of building your div as a string, you'll want to use document.createElement('div') . 与其将div构造为字符串,不如使用document.createElement('div') This way you will have a real dom object, and can get and set it's propeties, including onClick 这样,您将拥有一个真实的dom对象,并可以获取并设置它的属性,包括onClick

Try building the div as a DOM element first. 尝试首先将div作为DOM元素构建。

var myVar = document.createElement("div"),
    parentDiv = document.getElementById("parent_div");

parentDiv.appendChild(myVar);
myVar.innerHTML = "some clickable text";
if(myVar.addEventListener){
    myVar.addEventListener("click", clickFn, false);
}
else if(myVar.attachEvent){
    myVar.attachEvent("onclick", clickFn);
}
else{
    myVar.onclick = clickFn;
}

The addEventListener method is standard, but not every browser plays nice with the standard. addEventListener方法是标准的,但并不是每个浏览器都能很好地使用该标准。

EDIT: As mentioned, an element must be added to the DOM first. 编辑:如前所述,必须先将元素添加到DOM。

Will this help? 这会帮助吗? Since you dynamically generate it, you know the control id of the DIV. 由于您是动态生成的,因此您知道DIV的控件ID。

document.getElementbyId('abc').onClick = foo;
function foo()
{
alert("All your impl to go here");
}

Brian Glaz is totally right but, if for some reason, you really need to do it this way, you have two options: 布莱恩·格拉茨(Brian Glaz)完全正确,但是,如果出于某种原因,您确实需要这样做,则有两种选择:

you can only add events to something that is already in the DOM, using pure javascript, so you would have to include it in the html like: 您只能使用纯JavaScript将事件添加到DOM中已存在的事件中,因此您必须将其包含在html中,例如:

document.body.innerHTML += myVar;

and then, attach the event with 然后,将事件附加到

document.getElementById('abc').addEventListener('click', function(e){
   //your code
}, 1);

With jQuery, you could use .live() to attach events to elements that are not yet present in the DOM: 使用jQuery,您可以使用.live()将事件附加到DOM中尚不存在的元素:

 $('#abc').live('click', function(e){
    //your code here
 });

so you could add the div later... 因此您可以稍后添加div ...

Or you can use this technique: attach event to the document.body . 或者,您可以使用此技术:将事件附加到document.body Then if the event target is not the needed div than just do nothing. 然后,如果事件目标不是所需的div,则什么也不做。 It is the same techinque jquery uses for its live function: 这与技术jQuery的live功能使用的相同:

// crossbrowser event attachment function
function listen(evnt, elem, func) {
    if (elem.addEventListener) {
        elem.addEventListener(evnt, func, false);
    }
    else if (elem.attachEvent) {
        var r = elem.attachEvent("on" + evnt, func);
        return r;
    }
    else window.alert('I\'m sorry Dave, I\'m afraid I can\'t do that.');
}

// this is an analog of the jquery.live
var assignLiveEvent = function(id, evnt, callback) {
    var handler = function(e) {
        e = e || window.event;
        e.target = e.target || e.srcElement;

        if (e.target.id == id) {
            //your code here
            callback(e);
        }
    };

    listen(evnt, document.body, handler);
};

var myVar = "<div id='abc'>some clickable text</div>";

assignLiveEvent("abc", "click", function(e) {
    //your code here
});

// now you can add your div to DOM even after event handler assignation

Here is demo . 这是演示

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

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