如何简化此JavaScript/Angular代码?
如何简化此JavaScript/Angular代码?,javascript,html,arrays,angular,ternary,Javascript,Html,Arrays,Angular,Ternary,aria descripbeby需要在多个ID之间留一个空格aria 我试过这个,效果很好,但我的主管不高兴;他希望我使用数组简化它,但我不知道从哪里开始: var descripebyText=[this.error?this.errorId:”,this.help?this.helpId:”; var descripeby=descripebytext.join(“”); 然后在HTML中,我有以下内容: aria descripeby=“${ifDefined(descripeby?de
aria descripbeby
需要在多个ID之间留一个空格<不需要时,需要从
属性中取出由描述的代码>aria
我试过这个,效果很好,但我的主管不高兴;他希望我使用数组简化它,但我不知道从哪里开始:
var descripebyText=[this.error?this.errorId:”,this.help?this.helpId:”;
var descripeby=descripebytext.join(“”);
然后在HTML
中,我有以下内容:
aria descripeby=“${ifDefined(descripeby?descripeby:undefined)}”
存在多个ID时的结果是:
其中不需要由
描述的aria:
即使未设置
this.errorId
或this.helpId
中的一个,也始终会向数组中添加两个元素Array.prototype.join
不关心这些元素实际上是什么,只是将它们连接起来并在它们之间留出一个空格
因此,您最终得到的是descripeby==''
若要解决此问题,请仅在必须执行以下操作时向数组中添加元素:
var descripbedbytext=[];
if(this.errorId){
descripbedbytext.push(this.errorId);
}
if(this.helpId){
descripbedbytext.push(this.helpId);
}
var descripeby=descripebytext.join(“”);
关于从div中提取所描述的咏叹调,您可以这样做:
<div [attr.aria-describedby]="describedBy || null"></div>
对ARIA属性使用属性绑定,并根据descripbedby
值设置其值。如果descripeby
是空字符串,则将属性值设置为null
——这将从DOM中删除该属性