简体   繁体   English

单击按钮时Javascript显示div

[英]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. 我意识到这是一个常见的问题,我已经搜索了解决方案以及我尝试使用的解决方案(它在jsfiddle中有效),但是当我尝试在我的网站中使用它时,它将无法正常工作。 I'm trying to show a div when a button is clicked. 我试图在单击按钮时显示div。 Am I doing something wrong? 难道我做错了什么? Maybe there's something wrong with the javascript? javascript可能有问题吗? Or could it be I need to include a jquery js file? 还是我需要包括一个jQuery js文件? 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. .next() .parent()之后使用.parent() ,因为您是指按钮后的下一个元素...但是没有元素...所以您需要父元素的next()

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. 编辑:根据有关<HEAD>新信息,您在整个dom准备就绪之前正在执行代码...因此,您实际上是在将代码应用于任何内容。 You need to wait for the DOM to be ready. 您需要等待DOM准备就绪。 Like this 像这样

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

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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