jQuery事件附加到共享同一个类

时间:2015-11-03 17:04:38

标签: jquery html

我正在尝试找到一种将事件附加到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>
&#13;
&#13;
&#13;

基本上,我想知道的是我如何使用 class 标签而不是 id 标签为包含我单击的按钮的div着色而不是所有div。

我尝试在脚本末尾添加stopPropagation()return false但没有取得任何成功:(

2 个答案:

答案 0 :(得分:0)

不要使用.mother类定位所有元素,而是使用关键字this来引用要点击的元素,并使用.parent()选择其父元素:

$('.bouton').click( function(){
    $(this).parent().addClass('red');
});

<强> jsFiddle example

答案 1 :(得分:0)

使用jquery .closest()函数:

$('.bouton').click( function(){
    $(this).closest('.mother').addClass('red');
});

这将搜索DOM并找到与给定选择器匹配的最接近元素。看到工作小提琴:http://jsfiddle.net/1a27t3u4/3/