gpt4 book ai didi

javascript - 如何按类名选择元素并遍历angularJs中的那些对象?

转载 作者:太空宇宙 更新时间:2023-11-04 08:40:16 25 4
gpt4 key购买 nike

我是 angularJs 的新手,我在我的 Angular Controller 中有一个函数

$scope.addPrimaryClass = function () {
var weekDayBtn = $(".weekdayButton");
weekDayBtn.addClass("btn-white").removeClass("btn-primary");
$.each(weekDayBtn,function (index) {
if($(this).val()==$scope.weekly){
$(this).addClass("btn-primary").removeClass("btn-white");
}
})
};

在我看来:

<div class="btn-group">
<button class="btn btn-white weekdayButton" type="button" value="7" ng-click="weekdayClicked($event);">Sun</button>
<button class="btn btn-white weekdayButton" type="button" value="1" ng-click="weekdayClicked($event);">Mon</button>
<button class="btn btn-primary weekdayButton" type="button" value="2" ng-click="weekdayClicked($event);">Tue</button>
<button class="btn btn-white weekdayButton" type="button" value="3" ng-click="weekdayClicked($event);">Wed</button>
<button class="btn btn-white weekdayButton" type="button" value="4" ng-click="weekdayClicked($event);">Thu</button>
<button class="btn btn-white weekdayButton" type="button" value="5" ng-click="weekdayClicked($event);">Fri</button>
<button class="btn btn-white weekdayButton" type="button" value="6" ng-click="weekdayClicked($event);">Sat</button>
</div>

addPrimaryClass 中的代码在控制台中按要求工作,因为我可以在那里使用普通的 jquery,但代码本身在 angular 中不起作用。基本上,我想根据范围值之一更改按钮的 css。请帮忙!!!

最佳答案

您可以使用 ng-class 指令根据范围变量是什么来应用类。例如:

<button class="btn weekdayButton" type="button" value="7" ng-click="weekdayClicked($event);" ng-class="($(this).val()==$scope.weekly) ? 'btn-primary' : 'btn-white'">Sun</button>

ng-class 指令有多种使用方式。请查看文档并确定最适合您的内容:https://docs.angularjs.org/api/ng/directive/ngClass


另外,您可能希望从 Angular 代码中删除所有 jQuery :)

关于javascript - 如何按类名选择元素并遍历angularJs中的那些对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44176516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com