2015-03-31 50 views
0

我是JQuery的新手。有兩個HTML元素(P和輸入)。點擊一個按鈕,我想隱藏這兩個元素。兩者具有相同的類名。 簡單的代碼不起作用。 請提出任何建議。隱藏所有具有類名的元素

感謝很多 納特

<!doctype html> 
<html> 

<head> 
    <meta charset="utf-8"> 
    <title>Demo</title> 
</head> 

<body> <a href="http://jquery.com/">jQuery</a> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
    <script> 
     $(document).ready(function() { 
      $("#hide#").click(function() { 
       $(.test).hide(); 
      }); 
      $("#show").click(function() { 
       $(.test).show(); 
      }); 
     }); 
    </script> 
    <p class="test">Hello this is P element that I am trying to hide using its class</p> First name: 
    <input class="test1" type="text" name="fname"> 
    <button id="hide">Hide</button> 
    <button id="show">Show</button> 
</body> 

</html> 
+0

使用引號'$( 「測試 」)的'$'和'而不是$(「 #隱藏 」)'(「 #隱藏#」)' – Satpal 2015-03-31 16:48:49

+0

^^那,並在* #hide - '$(「#hide」)之後移除散列*另外,它們實際上並沒有相同的類。檢查輸入類;) – Archer 2015-03-31 16:51:10

回答

0

那麼,你的jQuery是畸形的。有問題#1:

$(document).ready(function(){ 
    $("#hide").click(function(){ //assuming "hide#" is the button's ID. 
    $('.test').hide(); 
    }); 
    $("#show").click(function(){ 
    $('.test').show(); 
    }); 
}); 

我也想改變「隱藏」按鈕的ID只是「隱藏」如果沒有準備好,在這種情況下。

您還忘記附上單引號/雙引號關閉您的選擇器,這就是爲什麼隱藏甚至沒有開始工作。

2

$(document).ready(function(){ 
 

 
    $('#hide').on('click', function(){ 
 
    $('.test').hide() 
 
    }); 
 

 
    $('#show').on('click', function(){ 
 
    $('.test').show() 
 
    }); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<p class='test'>some text1</p> 
 
<p class='test'>some text2</p> 
 

 
<button type='button' id='hide'>hide</button> 
 
<button type='button' id='show'>show</button>

+0

非常感謝你們。 – 2015-03-31 17:12:07

+0

非常感謝你們兩位。 – 2015-03-31 17:12:20

+0

當然,如果任何一個答案正在工作,那麼請將其標記爲「接受答案」以節省其他時間並避免他人回答此問題。謝謝! – Vim 2015-03-31 17:33:05

相關問題