문제

Everyone, I have a rather weird problem.

In an HMTL unordened list I have several list elements with onClick events, and they all call the same function.

<ul>
    <li onClick="Javascript:show(this.innerHTML); alert(this.innerHTML);">1</li>
    <li onClick="Javascript:show(this.innerHTML); alert(this.innerHTML);">2</li>
    <li onClick="Javascript:show(this.innerHTML); alert(this.innerHTML);">3</li>
    <li onClick="Javascript:show(this.innerHTML); alert(this.innerHTML);">4</li>
    <li onClick="Javascript:show(this.innerHTML); alert(this.innerHTML);">5</li>
    <li onClick="Javascript:show(this.innerHTML); alert(this.innerHTML);">6</li>
    <li onClick="Javascript:show(this.innerHTML); alert(this.innerHTML);">7</li>
    <li onClick="Javascript:show(this.innerHTML); alert(this.innerHTML);">8</li>
    <li onClick="Javascript:show(this.innerHTML); alert(this.innerHTML);">9</li>
    <li onClick="Javascript:show(this.innerHTML); alert(this.innerHTML);">0</li>
</ul>

This is the Javascript function:

function show(ID){
    show = document.getElementById(ID);
    notShow = document.getElementsByClassName("visible")[0];
    if (typeof notShow !== "undefined"){
        notShow.classList.toggle("hidden");
        notShow.classList.toggle("visible");
    }               
    show.classList.toggle("hidden");
    show.classList.toggle("visible");
}

for some unknown reason, the function works fine when I click one of the <li> elements first, but the second time I do that I get an error:

Uncaught TypeError: object is not a function ACNL.php:31

I think the error is not inside the javaScript function, but in the HTML-element that calls the function.

Any help would be appreciated!

도움이 되었습니까?

해결책

I see a few problems here. In no particular order:

  • It would probably be safest to change the inner variable name show to something else since your function is also called show(...).
  • Declare variables with the var keyword to avoid populating the top namespace.
  • You're retrieving DOM elements by ID, but none of your DOM elements (in the above example) have ID attributes. You'll want to add them to your li items at least, e.g. id="1"
  • If these elements don't have visible to start off with, you'll add both visible and hidden when you "toggle".
  • If you toggle visible and hidden on the li items, then notShow = document.getElementsByClassName("visible")[0]; should probably change, as you will be retrieving the li items once they have visible in them. Try using other class names or element types.

Here is a jsFiddle to get you started (ignore the window.show definition that's specific to jsFiddle).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top