2017-10-15 148 views

回答

0

基于original code for selection.text()我创建了selection.cachedText(),这是一个使用数据属性缓存文本的版本。这些属性访问/分配使用getAttribute/setAttributedataset is unsupported for SVG content in IE/Edge):

function textRemove() { 
    this.textContent = ""; 
} 

function textConstant(value) { 
    return function() { 
     if (this.getAttribute("data-text") !== value) { 
     this.textContent = value; 
     this.setAttribute("data-text", value); 
     } 
    }; 
} 

function textFunction(value) { 
    return function() { 
    var v = value.apply(this, arguments),; 
     text = v == null ? "" : v; 
    if (this.getAttribute("data-text") !== text) { 
     this.textContent = text; 
     this.setAttribute("data-text", text); 
    } 
    }; 
} 

d3.selection.prototype.cachedText = function(value) { 
    return arguments.length 
     ? this.each(value == null 
      ? textRemove : (typeof value === "function" 
      ? textFunction 
      : textConstant)(value)) 
     : this.node().textContent; 
}; 

的表现远远没有达到最佳,如https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes#Issues提到:

要考虑的主要问题是Internet Explorer的支持和性能。 Internet Explorer 11+为标准版提供支持,但所有早期版本为do not support dataset。为了支持IE 10,您需要使用getAttribute()来访问数据属性。另外,performance of reading data-attributes相比,将这些数据存储在JS数据仓库中效果很差。

因此,使用JS数据结构而不是DOM的解决方案会更好。