我正在制作一个社交网络图表,在工具提示中显示有关作家的信息。但是,有时我正在使用的数据库中的某些数据字段是空的,因此当您将鼠标悬停在节点上时,它不会显示任何内容(如果该字段为“”),或者显示未定义(如果该特定字段的整个字段)作者已被删除)。例如biography: ""
数据集中返回“传记:”,如果我删除该作者的传记字段,它将返回“传记:未定义”。
我尝试创建一个函数,如果字段中没有信息或未定义信息,则该函数将返回备份语句,但是(我认为)由于该函数位于 return 语句内,因此它不起作用。它只是返回写出的函数。
如果事实证明将函数放在 return 语句中不起作用,我可以尝试哪些替代方法(除了修复数据库等显而易见的方法之外)?我是编程新手,所以这可能是一个非常明显的错误。
fiddle :http://jsfiddle.net/Lv48w/
//code code code
bioBackup = function () {
if (d.biography = undefined || "") {
return "There is no listed biography for " + d.name
} else {
return d.biography}
};
//Add the tooltip
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return d.name +
"<br><span class='tipTitle'>Location:</span>" + " " + d.location +
"<br><span class='tipTitle'>Floruit Date:</span>" + " " + d.floruitDate +
"<br><span class='tipTitle'>Biography:</span>" + " " + bioBackup +
'<br>Click through for more information.';
});
//code code code
最佳答案
我稍微研究了一下你的 jsfiddle 链接并想出了一个解决方案。
如果您将工具提示变量代码替换为
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return d.name +
"<br><span class='tipTitle'>Location:</span>" + " " + d.location +
"<br><span class='tipTitle'>Floruit Date:</span>" + " " + d.floruitDate +
"<br><span class='tipTitle'>Biography:</span>" + " " + (d.biography ? d.biography : "There is no listed biography for " + d.name) +
'<br>Click through for more information.';
});
您可以完全摆脱 bioBackup
函数,并且它可以正常工作。
关于javascript - 将函数放入 return 语句中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24458494/