简体   繁体   中英

Javascript show div when button is clicked

I realize that this is a common question and I have searched for solutions and the one that I'm trying to use (it works in jsfiddle) but when I tried to use it in my website it just won't work. I'm trying to show a div when a button is clicked. Am I doing something wrong? Maybe there's something wrong with the javascript? Or could it be I need to include a jquery js file? Thanks for your help in advance.

Here is the code I'm trying to use:

<script type="text/javascript">
  $("#seeAnswer").click(function() {
    $('#subtext').html($(this).next().html());
  });
</script>

And I'm trying to use it with this:

<div class="back_button">
  <button id="seeAnswer">See Answer</button>
</div>
<span>
  <?php 
    /*  foreach($row2 as $ans) {
           $answer = $ans['answer'];
            }
   echo $answer;
   echo "hi";
  */
?>

    <?php foreach ($row2 as $ans) : ?>
        <p><?php htmlspecialchars($ans['answer']) ?></p>
    <?php endforeach ?>
      <p>hi there</p>
</span>

<div id="subtext">
</div>

Use .parent() after .next() because you are referring to the next element after the button... but there is no element... so you want the next() of the parent element.

EDIT: as per new information about the <HEAD> , you are executing the code before the whole dom is ready... so you're actually applying the code to nothing. You need to wait for the DOM to be ready. Like this

$('docment').ready(function() {
    $("#seeAnswer").click(function () {
        $('#subtext').html($(this).parent().next().html());
    });
});

Fiddle

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