2012-07-20 104 views
0

這是一個html頁面獲取jQuery中的元素的ID onlclick?

<span class ="title" id="title_1">this is</span> 
<span class="toggle" id="toggle_1>paragraph 1</span> 

<span class ="title" id="title_2">this is</span> 
<span class="toggle" id="toggle_2">paragraph 2</span> 

我嘗試做切換functon的onlcick事件的一個很簡單的例子,所以基本上當用戶點擊TITLE_1的toggle_1將隱藏和顯示,並在用戶點擊了title_2它會顯示並隱藏toggle_2,我希望這是有道理的。

(document).ready(function() { 
     $('.toggle').hide(); 
     $('#title_').click(function() { 
     $('#toggle_').toggle('slow'); 
    }); 
     }); 

我開始像我這樣的jQuery,只是不知道該從這裏做什麼。感謝

+1

作爲一個方面說明:我會用CSS來隱藏切換元素而不是jQuery的。否則,它只會在dom加載後纔會隱藏,這可能需要一些時間。 – Thomas 2012-07-20 11:11:19

+0

謝謝你會這麼做 – unknown 2012-07-20 11:15:49

回答

0

,你可以:

$('.toggle').hide(); 
$('.title').click(function() { 
    $(this).next(".toggle").toggle('slow'); 
}); 
0

這裏有一個簡單的方法,

HTML

<span class ="title" id="title_1">this is</span> 
<span class="toggle title_1">paragraph 1</span> 

<span class ="title" id="title_2">this is</span> 
<span class="toggle title_2" id="toggle_2">paragraph 2</span> 

jQuery的

$(document).ready(function() { 
     $('.toggle').hide(); 
     $('.title').click(function() { 
     $('.'+ $(this).attr("id")).toggle('slow'); 
    }); 
     }); 

我沒有測試的代碼。希望它能起作用。

0

試試這個

(document).ready(function() { 
     $('.toggle').hide(); 
     $('.title').click(function() { 
       $(this).closest('.toggle').toggle('slow'); 
     }); 
});