2013-06-27 56 views
4

我有一個簡單的DIV,不能讓它隱藏()和顯示()。爲什麼jQuery hide()和show()不起作用?

我想我做對了,但找不到它有什麼問題。

<div id="thediv" >hola</div> 
<input type="button" value="click to show">This is the div content</input> 

$(document).ready(function() { 
    $("div#thediv").hide(); 
    alert($("div#thediv").hide().attr("id")); 
}); 

$("button").click(function() { 
    $("div#thediv").show(); 
    alert('click'); 
}); 

另外,我創建了linkhttp://jsfiddle.net/rt9Fc/」 小提琴。

任何想法?

回答

8

把你的點擊處理程序中的document.ready和你選擇改變$("input:button") -

$(document).ready(function() { 
    $("div#thediv").hide(); 
    alert($("div#thediv").hide().attr("id")); 
    $("input:button").click(function() { 
     $("div#thediv").show(); 
     alert('click'); 
    }); 
}); 

演示--->JsFiddle

+0

太棒了!非常感謝。 – Luciano

1

您的按鈕選擇更改爲:button或使用輸入。 button選擇用於<button>Somebutton</button>

$(document).ready(function() { 

    var $thediv = $('#thediv').hide(); //Cache the object here. Also you can shain it through 

    $(":button").click(function() { 
    $thediv.show(); 
    alert('click'); 
}); 
}); 

Fiddle

如果你有ID,不標記名前綴它。它會使選擇器變慢。所以只需使用#thediv而不是div#thediv。如果你在多個地方使用jquery對象,也嘗試將jquery對象緩存到變量中,這樣可以避免調用jquery對象的創建時間。

1

更改按鈕selector:如您在使用簡單的<input type='button'/>仍然如果你想使用$('button')改變您的標記<button></button>

$("#thediv").hide(); 
alert($("div#thediv").hide().attr("id")); 


$("input[type='button']").click(function() { 
    $("#thediv").show(); 

}); 

DEMO-->JsFiddle

2

有代碼的更合適的版本:JsFiddle

HTML:

<div id="thediv">hola</div> 
<input type="button" value="click to show"/> 

的JavaScript:

$(function() { 
    var $myDiv = $("#thediv"); 
    $myDiv.hide(); 
    alert($myDiv.attr("id")); 

    $("input[type=button]").on('click', function() { 
     $myDiv.show(); 
     alert('click'); 
    }); 
}); 

一些有用的注意事項:

  • 高速緩存中找到的DOM元素怎麼一回事,因爲它們價格昂貴,上找到的,而不是點擊
  • 使用,它的工作速度更快
  • $(function()是document.ready的別名,寫入速度更快,通過網絡發送的字節數更少)
  • 你不必使用div#id選擇器,#id是足夠的,因爲id應該是唯一的你的頁面,而且這種方式後,jquery將使用findElementById javascript函數它不會執行額外的檢查div。
  • 有關於jQuery性能的很好的文章:artzstudio
  • 輸入不應該被分成打開和關閉標記。

也許你想有這樣的:

HTML:

<div id="thediv"> 
    hola 
    <input type="button" value="click to show"/> 
</div> 

這樣我們可以優化的JavaScript:

$(function() { 
    var $myDiv = $("#thediv"); 
    $myDiv.hide(); 
    alert($myDiv.attr("id")); 

    $myDiv.find("input[type=button]").on('click', function() { 
     $myDiv.show(); 
     alert('click'); 
    }); 
}); 
0

給一個ID按鈕

<div id="thediv">hola</div> 
<input type="button" id="btn" value="click to show"/> 

使用此代碼

$(document).ready(function() { 
$("div#thediv").hide(); 
alert($("div#thediv").attr("id")); 
}); 

$("input#btn").click(function() { 
$("div#thediv").show(); 
alert('click'); 
}); 
相關問題