简体   繁体   English

无法将课程添加到元素子级

[英]Cannot add class to element children

I'm trying to find an element in my HTML file based on its parent class name and then add a class to it. 我试图根据其父类名称在HTML文件中找到一个元素,然后向其中添加一个类。 I've tried the solution in here but it won't work. 我在这里尝试过该解决方案,但无法正常工作。 also, I've tried to log the child class name to see if it's working but it will return undefined . 另外,我尝试记录子类名称以查看其是否正常运行,但它将返回undefined My HTML file is something like this: 我的HTML文件是这样的:

 $(document).ready(function () { console.log($(".grid-container").find(">:first-child").className); $(".grid-container").find(">:first-child").toggleClass("search-controller"); }); 
 .search-controller { height: 100%; color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div ui-view="" class="grid-container ng-scope" style=""> <div ng-controller="citySearchController" ng-init="initialize()" class="ng-scope"> This is test data </div> </div> 

To get the class name from jQuery object you have to use prop() . 要从jQuery对象获取类名,必须使用prop() Try to set some style to the element so that the changes are visible (like color ): 尝试为元素设置某种样式,以使更改可见(如color ):

 $(document).ready(function () { console.log($(".grid-container").find(">:first-child").prop('class')); $(".grid-container").find(">:first-child").toggleClass("search-controller"); }); 
 .search-controller { height: 100%; color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div ui-view="" class="grid-container ng-scope" style=""> <div ng-controller="citySearchController" ng-init="initialize()" class="ng-scope"> This is test data </div> </div> 

Use addClass instead of toggleClass . 使用addClass而不是toggleClass toggleClass class will require an event like click to toggle the class. toggleClass类将需要一个事件,例如click以切换该类。

 $(document).ready(function() { //console.log($(".grid-container").find(">:first-child").className); $(".grid-container").find(">:first-child").addClass("search-controller"); }); 
 .search-controller { height: 100%; border: 1px solid green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div ui-view="" class="grid-container ng-scope" style=""> <div ng-controller="citySearchController" ng-init="initialize()" class="ng-scope">Test </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM