简体   繁体   中英

Simple JQuery click-and-show doesn't work

I'm using this simple bit of JQuery to show/hide a div by clicking on the link, I've used the same code a few times before and it worked perfectly but now all of a sudden it refuses to work.

JQuery is properly included and the page doesn't give a Javascript error (or any other error for that matter).

JQuery:

<script type="text/javascript"> 
   $(function() {
       $('#addnew').css('display', 'none');
       $('#shownew').click(function() {
           $('#addnew').toggle();
           return false;
       });        
   });
</script>

HTML (link):

<a href='#' id='shownew'>Add News Item</a>

HTML (div):

<div id="addnew">
<form id="new_news" enctype="multipart/form-data" action="news.php" method="post">
Title:
<br/><input type="text" name="title" id="title" />
<p>Image (optional, will be shown after first paragraph)
<br/><input type="hidden" name="size" value="2000000"><input type="file" name="photo">
<p>Article body:
<br/><textarea cols='40' rows='5' maxlength='5000' name='body' id='body'></textarea>
<p><input type="submit" name="submit" id="submit" value="Submit" />
</form>
</div>

What could I possibly be missing here? As you see from the JQuery, the div is hidden to begin with. When I remove the line that says $('#addnew').css('display', 'none'); the div is displayed correctly, but the link still doesn't toggle it on and off.

Is #showNew element present in the DOM before onload? If it is not then your code will not work. If that is the case following code will help you.

$(document).on('click', '#shownew',function() {
       $('#addnew').toggle();
       return false;
   }); 

I reloaded the page a few minutes later and it worked. No idea what was wrong. I know the code was good from the beginning.

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