Javascript 如何禁用来自循环的其他div(单击的div除外)
我有一些Javascript 如何禁用来自循环的其他div(单击的div除外),javascript,html,angular,typescript,local-storage,Javascript,Html,Angular,Typescript,Local Storage,我有一些li标记,其数据来自循环。当我单击任何li标记时,它将通过更改其图像而变为活动状态,并将存储到localstorage中,以便在刷新时,单击的标记仍处于活动状态。在这里,当我们单击时,一个活动对象正在向json添加单击的li标记,并将其存储在localstorage中。现在的问题是,当我再次单击已单击的li标记或其外部时,它会切换先前的图像,这不应该发生。同样,除单击的标签外,其他li标签应被禁用。下面是代码 app.component.html 在我看来,您只需要向toggleActi
li
标记,其数据来自循环。当我单击任何li
标记时,它将通过更改其图像而变为活动状态,并将存储到localstorage中,以便在刷新时,单击的标记仍处于活动状态。在这里,当我们单击时,一个活动对象正在向json添加单击的li
标记,并将其存储在localstorage中。现在的问题是,当我再次单击已单击的li
标记或其外部时,它会切换先前的图像,这不应该发生。同样,除单击的标签外,其他li
标签应被禁用。下面是代码
app.component.html
在我看来,您只需要向
toggleActive
方法添加一些逻辑。在决定是否对单击执行任何操作之前,可以检查是否有任何项目处于活动状态。这样能解决你的问题吗
有人能帮我一下吗?现在我从if中删除了第一个条件,但如何在点击后禁用其他未激活的li?恐怕我有点不确定你在问什么。您希望单击何时生效?您只需更新
if
条件以符合您的要求。单击任何li后,您将无法再次单击其他li。这些将被禁用如果用户再次单击相同的li
,会发生什么情况?其他的应该再次启用吗?不,不会发生任何事情
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<div>
<pre>
</pre>
<ul>
<li *ngFor="let item of statusdata" (click)="toggleActive(item, !item.active)">
<span>{{item.id}}</span>
<span>{{item.name}}</span>
<span>
<img *ngIf="!item?.active || item?.active === false" src ="https://dummyimage.com/qvga" />
<img *ngIf="item?.active === true" src ="https://dummyimage.com/300.png/09f/fff" />
</span>
</li>
</ul>
</div>
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
statusdata: any;
ngOnInit() {
this.statusdata = [
{ id: 1, name: "Angular 2" },
{ id: 2, name: "Angular 4" },
{ id: 3, name: "Angular 5" },
{ id: 4, name: "Angular 6" },
{ id: 5, name: "Angular 7" }
];
this.statusdata.forEach(item => {
this.getCacheItemStatus(item);
});
}
toggleActive(item, activeStatus = true) {
item.active = activeStatus;
localStorage.setItem(`item:${item.id}`, JSON.stringify(item));
}
getCacheItemStatus(item) {
const cachedItem = localStorage.getItem(`item:${item.id}`);
if (cachedItem) {
const parse = JSON.parse(cachedItem); // Parse cached version
item.active = parse.active; // If the cached storage item is active
}
}
}
toggleActive(item, activeStatus = true) {
if(item.active || !this.statusdata.some(d => d.active)){
item.active = activeStatus;
localStorage.setItem(`item:${item.id}`, JSON.stringify(item));
}
}