I've been trying to learn something about JavaScript today, came across events and somehow I'm stuck at it.

When I call the first function it just works, however if I call the second one it doesn't execute the function for some reason? I've tried doing it without the windows.onload event I've tried putting the script code inside head element or just above the closing body tag but nothing has changed, any tips?

function peh() {
    
    document.onclick = function(){
    alert("you clicked");
}
}

function second(){
    var myElement = getElementsByTagName("mImg");
    myElement.onclick = function(){
        alert("clicked img");
    }
}

window.onload = function() {
    second();
}
有帮助吗?

解决方案 2

You use getElementsByTagName which receives the DOM HTML tag name, say, 'td' Better use getElementsById, as I guess mImg is an ID of some element...

其他提示

I guess you have to change your code like that :

function second(){
   var myElement = document.getElementsByTagName("mImg");
   myElement[0].onclick = function(){
    alert("clicked first img");
   }
}

Because getElementsByTagName selector is returning array. And you can make it "for" or "while" loop for each element.

Thanks to jquery framework you will not bother yourself about those things anymore . just use jquery functions .

$(document).ready(function(){
$(mImg).click(function(){
   alert("goood");
 });
});

or for dynamic tags :

$(document).on("click","mImg",function(){
alert("goood");
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top