开发者

Adding onclick event to li element in IE6

So I have a list, and I want to dynamically add an event via JavaScript. I have it working great in Firefox, but I also need it to work in IE6 (ugh), but it's required. It doesn't have to be pretty, just needs to work. The event that triggers simply removes the item from the list. I am not sure what I need to do to get it working. Here is small piece of what I have so far. The ids are unique, I just put that one in as an example. It works great in all newer browsers.

    var id = "123456";
    var list = document.createElement("ul");
    var listElement = document.createElement("li");
    listElement.setAttribute("id", id);
    listElement.setAttribute("onclick", "removeFromList('" + id + "')");
    listElement.appendChild(document.createTextNode(content));
    list.appendChild(listElement开发者_Go百科);
    document.getElementById('myElement').appendChild(list);


i don't have an IE6 to test this, but replacing the onclick-line:

listElement.setAttribute("onclick", "removeFromList('" + id + "')");

with this might work:

listElement.onclick = function(){ removeFromList(id); };

you also could use attachEvent for IE and stick to you old solution (or better use addEventListener) on the newer ones.


Pure javascript, should work in IE6 :

var id = "123456";
var list = document.createElement("ul");
var listElement = document.createElement("li");
listElement.setAttribute("id", id);
listElement.appendChild(document.createTextNode(content));
list.appendChild(listElement);
document.getElementById('myElement').appendChild(list);

if( listElement.addEventListener ) {
    listElement.addEventListener("click", function(e) {
        removeFromList( id );}, false );
} else {
    listElement.attachEvent( "onclick", function(e) {
        removeFromList( id );});
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜