[英]Jquery - Target 1 div with .click()
This might be a beginners question, but I'm at a loss. 这可能是一个初学者的问题,但我很茫然。
My objective is to have a button that when pressed the class that the button was in does something... if that makes sense.. Here is my code for my content on the page: 我的目标是有一个按钮,按下按钮所在的类做了一些事情......如果这是有意义的..这是我在页面上的内容的代码:
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();
}
So that code loops about 25 times and then in my content
div I have a nice list of the sites I want. 所以代码循环大约25次然后在我的content
div中我有一个很好的我想要的网站列表。 My next piece of code is: 我的下一段代码是:
$("#dropDown").click(function() {
$('.card').toggle();
});
The problem I am having is that when I press on the dropDown
button the image card
is supposed to appear for only 1 div, instead, images are showing up for each div, and I just want to target the div that the button was in. How would I do that? 我遇到的问题是,当我按下dropDown
按钮时,图像card
应该只显示1个div,而是显示每个div的图像,我只想定位按钮所在的div。我该怎么办?
Use 采用
$('#content').on('click', "#dropDown", function() {
$(this).next('.card').toggle(); //Use next()
});
As you are generating elements dynamically. 正在动态生成元素。 You should use Event Delegation using .on() delegated-events approach. 您应该使用.on()委托事件方法来使用事件委派 。
Also Important: IDs must be unique , So I would suggest you to use class selector like 同样重要: ID必须是唯一的 ,所以我建议你使用类选择器
To generate element use 生成元素使用
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();
}
Event Binding 事件绑定
$('#content').on('click', ".dropDown", function() {
$(this).next('.card').toggle(); //Use next()
});
In order to bind event to dynamically generated elements, you should use .on()
: 为了将事件绑定到动态生成的元素,您应该使用.on()
:
http://api.jquery.com/on/ http://api.jquery.com/on/
It also works for non-generated elements. 它也适用于非生成元素。
It is bad thing to have more than one element with the same id, but you can use something like this: 拥有多个具有相同ID的元素是件坏事,但您可以使用以下内容:
$("#dropDown").click(function() {
$(this).find('.card').toggle();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.