简体   繁体   中英

javascript resets the css value after a href onclick

this is the html line where i call the function:

<a href="" onclick="showMe(0);">Oranges</a>

and this is the javascript:

function showMe (whichClass) {

    var fruitShow = document.getElementsByClassName('fruit')[whichClass];

    fruitShow.style.display = 'inline';    
}

it works when i click the link and displays the fruit but it disappears. When the site loads the fruits are all set to display: none, i'm not sure if its reverting back or something else is going on. I have also tried using return before the function call (return showMe(1);)

Clicking the link triggers a reload of the page. Passing an empty value to href is equivalent to using the URL of the current page.

There are a couple of ways to prevent the page from following the link:

  • Change the href value to "#" . This will make the page jump scroll to the top though, so you probably have to do the next option either way.

  • Stop the default behavior via event.preventDefault() . The default behavior is to load the URL. You can prevent that via the event object :

     onclick="event.preventDefault();showMe(0)"; 

    (note: while this works, there are better ways to bind event handlers )

  • Better yet : Don't use a link (since you don't link to anything), use a <button> instead. You can style it anyway you like with CSS.

Try changing your anchor href from "" to # .

replace

<a href="" onclick="showMe(0);">Oranges</a> 

with

<a href="#" onclick="showMe(0);">Oranges</a>

Or this

<a href="" onclick="showMe(0);">Oranges</a>

change to this (prevent jumping)

<a href="#void" onclick="showMe(0);">Oranges</a>

Just to have a tip more, but as already pointed out, using a button on this situation is a better solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM