开发者

JavaScript OnClick returning error Object is not a function

I have a function where when an element is clicked, it makes that element the selected element in a an Object. Let me show you.

var elem = new Object();
elem = {
    title:'',//string
    num:null,//number
    selected:null
}
function selected(elem){
    elem.title = elem.getAttribute("title") || this['title'];
    alert(elem.title);
    for(x=0;x<classIds.length;x++){
        if(elem.title==classIds[x].name){
            elem.num=x; 
            elem.selected=classIds[x];
            alert(elem.selected.properties);
        }
    }
}

So when an element is clicked, the selected function runs from an onlick attr on the element. Which is cool. It works fine. But, if you click on it again, the browser gives the error Object is not a function. This only happens when you click on the same element consecutively. If开发者_如何学运维 you click on another element, it doesn't happen. Which is weird because the function should be running a seperate time and overwriting the Object elem (which is defined outside the function as a global variable/object). I have the alert for reasons of debugging. Also, the array classIds is defined out of the function as well. Any insight would be great. Also, I know my coding is a little odd, I am really just starting with Objects and Methods in JavaScript.

Edit

Onclick is called like this below

<li title="+classIds[x].name+" onclick='selected(this)'>"+classIds[x].name+"</li>

So...

onclick='selected(this)'

Is the the call


There's one really obvious problem in your code: you're declaring a global variable (outside your function) called elem, and then your function has a parameter also called elem. So every reference to elem within the function will be to the parameter not to the global. Given how you're calling the function the parameter refers to your <li> element so that means the function is currently overwriting and/or creating properties on that element.

If you change the name of the parameter, to say clickedElem then within the function you can use elem when you mean the global variable and clickedElem when you mean the parameter.

Beyond that I'm not quite sure what you're trying to achieve so I don't know what else to advise.

(And as an aside, as I said in a comment above, there's no point initialising elem = new Object() because on the next line you immediately assign it equal to something else. But that isn't going to cause you a problem, it's just pointless.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜