jQuery切换不起作用

时间:2015-12-17 04:29:16

标签: javascript jquery

var resultsList = $("#test");
resultsList.text("Hello. This is jQuery!");

var tB = jQuery("#toggleButton");

tB.on("click", function() {
    resultsList.toggle(400);
});

我认为语法是正确的,因为浏览器控制台没有报告任何错误。

加载页面时,切换功能未按预期工作。任何想法,我在这里缺少什么?

我的HTML是:

<div id="results" class="bordered-image"> 
    <button id="#toggleButton">Hide</button> 
    <div id="test">This is where results will live...eventually.</div>     
</div>

5 个答案:

答案 0 :(得分:2)

将Jquery代码放入document.ready(),如下所示:同时检查Fiddle

$(document).ready(function(){
       var resultsList = $("#test");
        resultsList.text("Hello. This is jQuery!");

        var tB = jQuery("#toggleButton");

        tB.on("click", function() {
            resultsList.toggle(400);
        });
    });

您的id属性应为id =&#34; toggleButton&#34;而不是id =&#34; #toggleButton&#34;

<强> HTML

<div id="results" class="bordered-image"> 
    <button id="toggleButton">Hide</button> 
    <div id="test">This is where results will live...eventually.</div>     
</div>

答案 1 :(得分:0)

将其包裹在文档就绪功能中。

答案 2 :(得分:0)

id =“toggleButton”而非id =“#toggleButton”将会这样做。

答案 3 :(得分:0)

见这个例子。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<div id="results" class="bordered-image"> 
    <button id="toggleButton">Hide</button> 
    <div id="test">This is where results will live...eventually.</div>     
</div>

</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
   var resultsList = $("#test");
    resultsList.text("Hello. This is jQuery!");
    $("#toggleButton").click(function() {
        resultsList.toggle(400);
    });
});
</script>
</html>

由于 阿米特

答案 4 :(得分:0)

<div id="results" class="bordered-image"> 
<button id="#toggleButton" onclick="myff();">Hide</button> 
 <div id="test">This is where results will live...eventually.</div>     
</div>

 <script>
 function myff(){

  $("#test").toggle();  
  }

</script>