我试图根据其父类名称在我的 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>
关于javascript - 无法将类添加到元素子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51374403/