通过 D3 选择和过滤更改 JavaScript 中的类



我有一个如下函数。

首先,我将所有类更改为"徽章徽章-次要"。 然后,检查跨度中的文本。如果它是"右"并单击,则更改为"徽章徽章-主要"。 否则,它是"错误"并点击,更改为"类","徽章徽章危险"。

我可以让我的代码更简洁、更正确吗?

function updateOrderType(ansType) {
lastAnsType = ansType;
var ansBadge = d3.select("#anstype").selectAll("span.badge");
ansBadge.attr("class", "badge badge-secondary");
ansBadge.filter(function() {
if (d3.select(this).text() == ansType) {
return d3.select(this).text() == "right";
}
}).attr("class", "badge badge-primary");
ansBadge.filter(function() { 
if (d3.select(this).text() == ansType) {
return d3.select(this).text() == "wrong";
}
}).attr("class", "badge badge-danger");
}

我认为您的代码有点难以理解,但根据您在介绍中编写的逻辑,我建议使用以下方法:

function updateOrderType(ansType) {
var ansBadge = d3.select("#anstype").selectAll("span.badge");
ansBadge.forEach(function() {
var oElement = d3.select(this);
if (/**CLICKED**/) {
var sText = oElement.text();
if(sText === "right") {
oElement.setAttribute("class", "badge badge-primary");
} else if(sText === "wrong") {
oElement.setAttribute("class", "badge badge-danger");
} else {
oElement.setAttribute("class", "badge badge-secondary");
}
} else {
oElement.setAttribute("class", "badge badge-secondary");
}
}
}

您的代码遍历ansBadge数组几乎 5 次,每轮计算 1个 if语句。我上面的建议迭代了 1 次,顶部有 3个 ifs。如果您检查元素是否被单击(在外部if中(,您甚至可以改进这一点,因为更有可能是这种情况。

在此代码中,处理四种类型的元素:

  • 单击和"正确">主要
  • 点击和"错误">危险
  • 点击任何文本>辅助文本
  • 未单击任何文本>辅助文本

Georgina95答案的简化

function updateOrderType(ansType) {
var ansBadge = d3.select("#anstype").selectAll("span.badge");
ansBadge.forEach(function() {
var oElement = d3.select(this);
var newClass = "badge badge-secondary";
if (/**CLICKED**/) {
var sText = oElement.text();
if(sText === "right") {
newClass = "badge badge-primary";
} else if(sText === "wrong") {
newClass = "badge badge-danger";
}
}
oElement.setAttribute("class", newClass);
}
}

感谢您的帮助。 首先,我不能将forEach与 d3.select (v4( 一起使用。这是一个不使用attrsetAttribute的对象。所以我必须更改我的代码:

function updateOrderType(ansType) {
d3.select("#ordertype").selectAll("span").each(function() {
var badgeText = this.textContent;
if(ansType === badgeText) {
if(ansType === "right") {
this.setAttribute("class", "badge badge-primary");
} else if (ansType === "wrong") {
this.setAttribute("class", "badge badge-danger");
} else {
this.setAttribute("class", "badge badge-secondary");
}
} else {
this.setAttribute("class", "badge badge-secondary");
} 
});
}

最新更新