d3.js - 如何捕捉xlink :href errors in D3?

标签 d3.js error-handling

transition.select("image")
    .attr("xlink:href", function(d) {
      //fix icon error if icon does not exist in folder
      return 'assets/64pxBlue/file.png';
      // return d.icon
    })
    .attr("x", function(d) {return d.position_x ? d.position_x : '0px'})
    .attr("y", function(d) {return d.position_y ? d.position_y : '-10px'})
    .attr("width", function(d) {return d.value ? d.value : '20px'})
    .attr("height", function(d) {return d.value ? d.value : '20px'})
}

我正在尝试以PNG形式可视化文件。解析字符串后;它将匹配具有相应png并呈现的字符串。但是,我没有所有可能的png,因此如果我的assets/64pxBlue/目录中不存在默认的png,则需要返回它。

在我的devtools中,有一个GET错误。如何捕获该错误,并在出现错误时返回file.png?

最佳答案

D3没有任何支持此功能的方法,但是您可以使用以下简单的js来实现:

d3.selectAll("img")[0].forEach(function(i, n){
  i.onload=imageFound;//on error call this function
  i.onerror=imageNotFound;//on success call this function
  if (n ==0)
 	i.src="http://www.w3schools.com/html/pic_mountain.jpg";
  else
    i.src="http://www.w3schools.com/html/blah-blah.jpg";//set a wrong url
})


function imageFound() {
    console.log('That image is found and loaded');
}

function imageNotFound(me) {
    //set default url in case image not found
    me.target.src="http://www.w3schools.com/tags/smiley.gif";
    console.log("defaut image")
}

    
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<img  alt="Mountain View" style="width:304px;height:228px;">

<img alt="Mountain View" style="width:304px;height:228px;">

关于d3.js - 如何捕捉xlink :href errors in D3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36368530/

相关文章:

javascript - 使用 D3.csv 在 DC.JS 中加载 CSV 文件

javascript - 鼠标悬停前查找元素的原始颜色

javascript - 使用 D3.js 在 map 上绘制节点和边的网络

validation - flutter 中的字符串未删除空格

python - 处理 float 参数python

javascript - D3 : change font size of axis labels

d3.js - d3 : make the d3. csv 函数同步

php - 如何正确管理 PHP4 中的触发错误

ruby-on-rails - capybara 犯了两次错误,该如何拯救?

c# - 如何检查异步 Web 服务调用的错误