无法向元素子元素添加类

问题描述 投票:1回答:2

我正在尝试根据其父类名在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>
javascript html css kendo-ui kendo-grid
2个回答
2
投票

要从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>

0
投票

使用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>
© www.soinside.com 2019 - 2024. All rights reserved.