Adding onclick event to li element in IE6

僤鯓⒐⒋嵵緔 提交于 2020-01-05 07:33:52

问题


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);
    document.getElementById('myElement').appendChild(list);

回答1:


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.




回答2:


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 );});
}


来源:https://stackoverflow.com/questions/7529358/adding-onclick-event-to-li-element-in-ie6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!