2017-10-15 122 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的解決方案會更好。