[英]Target a specific element inside of the div that was click without using jQuery
[英]Jquery - Target 1 div with .click()
這可能是一個初學者的問題,但我很茫然。
我的目標是有一個按鈕,按下按鈕所在的類做了一些事情......如果這是有意義的..這是我在頁面上的內容的代碼:
if(domain == 'google.com') {
$('#content').append('<div id="highlight"><h1 id="headline">'+title+'</h1><img id="dropDown" src="images/small-dropdown.png" alt=""/><img class="card" src="'+URL+'"/></div></br>');
$('.card').hide();
}
所以代碼循環大約25次然后在我的content
div中我有一個很好的我想要的網站列表。 我的下一段代碼是:
$("#dropDown").click(function() {
$('.card').toggle();
});
我遇到的問題是,當我按下dropDown
按鈕時,圖像card
應該只顯示1個div,而是顯示每個div的圖像,我只想定位按鈕所在的div。我該怎么辦?
采用
$('#content').on('click', "#dropDown", function() {
$(this).next('.card').toggle(); //Use next()
});
正在動態生成元素。 您應該使用.on()委托事件方法來使用事件委派 。
同樣重要: ID必須是唯一的 ,所以我建議你使用類選擇器
生成元素使用
if(domain == 'google.com') {
$('#content').append('<div id="highlight"><h1 id="headline">'
+ title +'</h1><img class="dropDown" src="images/small-dropdown.png" alt=""/><img class="card" src="'+URL+'"/></div></br>');
$('.card').hide();
}
事件綁定
$('#content').on('click', ".dropDown", function() {
$(this).next('.card').toggle(); //Use next()
});
擁有多個具有相同ID的元素是件壞事,但您可以使用以下內容:
$("#dropDown").click(function() {
$(this).find('.card').toggle();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.