我正在尝试根据其父类名在HTML文件中找到一个元素,然后向其中添加一个类。我在here尝试过这个解决方案,但它不起作用。另外,我已经尝试记录子类名称以查看它是否正常工作,但它将返回undefined
。我的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>
要从jQuery对象获取类名,您必须使用prop()
。尝试为元素设置一些样式,以便更改可见(如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>
使用addClass
而不是toggleClass
.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>