Html按钮onclick事件无法正常工作

时间:2017-03-09 18:43:28

标签: javascript jquery html css

我想要html按钮“News”来显示我的div“New”,这里隐藏着我的代码(现在它不能正常工作):

<div id = "Buttons">
    <button id="News">News</button><br>
    <button id="Marks">Marks</button><br>
    <button id="Averages">Averages</button><br>
    <button id="Forum">Forum</button><br>
</div>  
<div id="New">
    <p id="Newer">Text</p>
</div>

#New{
        display: none;
        width: 500px;
        height: 500px;
        background-color: grey;
}

$(document).ready(function(){
    $("#News").click(function() {
        $("#New").show();
    });
});

3 个答案:

答案 0 :(得分:2)

<div id = "Buttons">
    <button id="News">News</button><br>
    <button id="Marks">Marks</button><br>
    <button id="Averages">Averages</button><br>
    <button id="Forum">Forum</button><br>
</div>  
<div id="New">
    <p id="Newer">Text</p>
</div>

<style>          <---------------this
#New{
        display: none;
        width: 500px;
        height: 500px;
        background-color: grey;
}
</style>          <---------------this

<script>          <---------------this
$(document).ready(function(){
    $("#News").click(function() {
        $("#New").show();
    });
});
</script>         <---------------this

答案 1 :(得分:1)

您不能将样式和脚本作为文本放入HTML页面。您必须告诉浏览器它应该如何处理代码。

首先,您需要将代码包装在适当的标记中:

<style>
#New{
    display: none;
    width: 500px;
    height: 500px;
    background-color: grey;
}
</style>
<script>
$(document).ready(function(){
    $("#News").click(function() {
        $("#New").show();
    });
});
</script>

其次,您需要确保在脚本标记之前包含JQuery:

<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<div id = "Buttons">
    <button id="News">News</button><br>
    <button id="Marks">Marks</button><br>
    <button id="Averages">Averages</button><br>
   <button id="Forum">Forum</button><br>
</div>  
<div id="New">
    <p id="Newer">Text</p>
</div>

答案 2 :(得分:0)

我假设你的榜样缩短了。这意味着,我假设你有<script><style>。如果没有,那些是必要的。另外,我会认真考虑重新命名你的一些东西。例如,只要您有一个表示一系列相似元素的包装器,就使用类名而不是id。例如,我会用类替换你的div而不是id:

<div class="buttons">
    <button id="news">News</button><br>
    <button id="marks">Marks</button><br>
    <button id="averages">Averages</button><br>
    <button id="forum">Forum</button><br>
</div>  

<div id="New">
    <p id="Newer">Text</p>
</div>

话虽如此,如果您添加适当的标记,您的代码将按原样运行:

<div class="buttons">
    <button id="news">News</button><br>
    <button id="marks">Marks</button><br>
    <button id="averages">Averages</button><br>
    <button id="forum">Forum</button><br>
</div>  

<style>
    #New{
        display: none;
        width: 500px;
        height: 500px;
        background-color: grey;
    }
</style>

<script>
    $(document).ready(function(){
        $("#News").click(function() {
            $("#New").show();
        });
    });
</script>