我试图找到一种将事件附加到DOM的特定元素的好方法。该元素与其他元素共享相同的类(实际情况:通过循环遍历DB生成20个div)。
为了使它尽可能简单,我在这里创建了一个可用的JSfiddle:jsfiddle.net/1a27t3u4/
事件很简单,只是向特定的div添加了一个类:
$('.bouton').click( function(){
$('.mother').addClass('red');
});.mother
{
width: 400px;
height: 100px;
margin-top: 20px;
margin-left: auto;
margin-right: auto;
border: 2px solid red;
text-align: center;
}
.red
{
background: red;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
HTML:
<div class="mother">
<button class="bouton"> Click me! </button>
</div>
<div class="mother">
<button class="bouton"> Click me! </button>
</div>
<div class="mother">
<button class="bouton"> Click me! </button>
</div>
<div class="mother">
<button class="bouton"> Click me! </button>
</div>
<div class="mother">
<button class="bouton"> Click me! </button>
</div>
基本上,我想知道的是如何通过使用类标记而不是id标记来给包含我单击的按钮的div颜色,而不是所有div。
我尝试在脚本的末尾添加stopPropagation()或return false,但没有成功:
发布于 2015-11-03 17:07:47
使用jquery .closest()函数:
$('.bouton').click( function(){
$(this).closest('.mother').addClass('red');
});这将搜索DOM并找到与给定选择器匹配的最接近的元素。见工作小提琴:http://jsfiddle.net/1a27t3u4/3/
https://stackoverflow.com/questions/33505029
复制相似问题