2017-07-19 41 views
0

我有這個我們正在爲學校的響應式設計練習所做的這個非常基本的網站(http://cimoril.dothome.co.kr/greece/aegean.html),我想爲每篇文章添加一個onClick事件。如何顯示/隱藏每篇文章/對象的類別?

我該如何讓它每篇文章而不是每堂課都能工作?例如,當我點擊其中一篇文章時,我只想顯示特定文章的類,而不是每篇文章。如果您單擊第一張圖片,則所有具有.text類的文章也會出現。

剛開始學習JS/jQuery,所以我不能很好地解釋,並且一直沒有能夠找到答案,同時谷歌搜索了一會兒..我提前道歉。

代碼段:

$(".text").hide(); 
 

 
$("article").on("click", function() { 
 
    $("p.text").show(); 
 
}); 
 

 

 
$("article").on("mouseleave", function() { 
 
    $("p.text").hide(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<section> 
 
    <article> 
 
    <div class="bg bg1"> 
 
     <span>Aghios Efstratios</span> 
 
     <p class="text text1">Aghios Efstratios is a small Greek island southwest of Lemnos and northwest of Lesbos.</p> 
 
    </div> 
 
    </article> 
 

 
    <article> 
 
    <div class="bg bg2"> 
 
     <span>Chios</span> 
 
     <p class="text text2">Chios is the fifth largest of the Greek islands, situated in the Aegean Sea</p> 
 
    </div> 
 
    </article> 
 
</section>

+1

歡迎的StackOverflow!請[編輯]您的問題以顯示相關HTML的示例。 (不要只依賴到外部網站的鏈接。) – nnnnnn

+0

謝謝你,對不起,我認爲在那裏檢查代碼會更容易。我編輯了我的第一篇文章。希望這可以幫助。 –

回答

2

您可以使用點擊事件中this參考,以獲得點擊事件發生的元素。然後你可以得到該文章元素中的段落。

在旁註中,您不需要很多$(document).ready()處理程序。你可以將它們組合成一個(除非你有特定的理由這麼做)。

例如

$(".text").hide(); 
 

 
$("article").click(function() { 
 
    $(this).find("p.text").show(); 
 
}); 
 

 
$("article").mouseleave(function() { 
 
    $(this).find("p.text").hide(); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<section> 
 
    <article> 
 
    <div class="bg bg1"> 
 
     <span>Aghios Efstratios</span> 
 
     <p class="text text1">Aghios Efstratios is a small Greek island southwest of Lemnos and northwest of Lesbos.</p> 
 
    </div> 
 
    </article> 
 

 
    <article> 
 
    <div class="bg bg2"> 
 
     <span>Chios</span> 
 
     <p class="text text2">Chios is the fifth largest of the Greek islands, situated in the Aegean Sea</p> 
 
    </div> 
 
    </article> 
 
    <section>

+0

非常感謝。這比我想象的要容易......不,我沒有一個具體的理由來準備好處理程序,我只是不知道如何編寫代碼。我很欣賞這樣一個簡單的問題的幫助^^ –

+0

不客氣!如果有幫助,請接受答案。 – H77

相關問題