2017-04-12 48 views
0

當輸入元素集中時,我無法讓此jquery添加類。當輸入元素集中時,jQuery addClass

(function($) { 

$('input.input-text').focus(function(){ 
    $(this).parent('p').addClass('focused_on'); 
}); 

}); 

它應該在輸入焦點時將「focused_on」類添加到父p元素。

下面是HTML:

(function($) { 
 

 
    $('input.input-text').focus(function() { 
 
    $(this).parent('p').addClass('focused_on'); 
 
    }); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p class="form-row form-row form-row-first validate-required" id="billing_first_name_field"><label for="billing_first_name" class="">First 
 
    Name <abbr class="required" title="required">*</abbr></label><input type="text" class="input-text " name="billing_first_name" id="billing_first_name" placeholder="" autocomplete="given-name" value="" /></p>

我在做什麼錯?

+1

。在你輸入標籤的類屬性尾隨空間 – user2182349

回答

0

你的包裝函數沒有被調用。看看這個:

(function($) { 

}); 

這定義了一個匿名函數,但不運行它。爲了運行一個功能,你需要的(),因爲你正在傳遞的jQuery,你需要這樣做:

(function ($) { 

})(jQuery); // runs function, and passes in jQuery 
1

在結束行這麼做 })(jquery);

0

.parent() 我檢查刪除'p'。所有的工作

並添加$(document).ready

$(document).ready(function($) { 

$('input.input-text').focus(function(){ 
    $(this).parent().addClass('focused_on'); 
}); 

});