2017-02-19 7 views
1

は、だから、中に - 私のクリックのみ背景色を変更することが可能であるだけ - 私がテキストフィールドに

$('.parent > *') 
 
    .focus(function() { 
 
     $('.parent').addClass('focused'); 
 
    }) 
 
    .blur(function() { 
 
     $('.parent').removeClass('focused'); 
 
    });
.parent {background: green} 
 
.focused {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="parent"> 
 
    <input class="childInput" type="text" /> 
 
    <div class="sibling"></div> 
 
</div> 
 
<br><br> 
 
<div class="parent"> 
 
    <input class="childInput" type="text" /> 
 
    <div class="sibling"></div> 
 
</div>

をクリックすると、その要素で、この機能を入れて、それは可能ですか? parentクラスと

$('.parent').addClass('focused'); 

だから、基本的にすべての要素:

答えて

2

これはすべての一致する要素を識別します。あなたがクリックされた子供の代わりに、選択したクラス.parentを持つすべての要素の親を選択する必要があります

$(this).closest('.parent').addClass('focused'); 
2

:代わりに、あなただけ最も近い一致する要素が欲しいです。イベントハンドラの内部

$('.parent > *') 
    .focus(function() { 
     $(this).closest('.parent').addClass('focused'); 
    }) 
    .blur(function() { 
     $(this).closest('.parent').removeClass('focused'); 
    }); 

一部$(this).closest('.parent')クリック要素thisを取ると、最も近い.parentを選択します。

これは.closestのドキュメントです:https://api.jquery.com/closest/

0
You have to select each element parent. So you have to use this selector for select a particular element. 

$('.parent > *') 
    .focus(function() { 
     $(this).parent('.parent').addClass('focused'); 
    }) 
    .blur(function() { 
     $(this).parent('.parent').removeClass('focused'); 
    }); 
</script> 
関連する問題