D3选择.attr,.property等setter方法'值未定义时的行为

d3 selection .attr, .property, etc setter methods' behaviour when value is undefined

本文关键字:未定义 attr 选择 property 方法 setter D3      更新时间:2023-09-26

调用d3.select("input[type=checkbox]").property("checked", undefined)时的预期行为是什么?

应该将其视为false,从而将checked属性设置为false/删除,还是应该将其视为无值,从而像调用getter .property("checked")一样?

属性方法

d3_selectionPrototype.property = function (name, value) {
    if (arguments.length < 2) {
        if (typeof name === "string") return this.node()[name];
        for (value in name) this.each(d3_selection_property(value, name[value]));
        return this;
    }
    return this.each(d3_selection_property(name, value)); 
}; 

当你传入值undefined时,因为你已经传入了2个参数,它调用d3_selection_property(对于选择中的每个条目),这是

function d3_selection_property(name, value) {
    function propertyNull() {
        delete this[name];
    }
    function propertyConstant() {
        this[name] = value;
    }
    function propertyFunction() {
        var x = value.apply(this, arguments);
        if (x == null) delete this[name]; else this[name] = x;
    }
    return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; }

非严格比较(最后一行)value == null在value === undefined时求值为true,因此调用propertyNull执行此操作

delete this[name];

但是,由于checked属性实际上不在this对象上(它实际上在DOM元素的原型链的上一级),因此这实际上没有任何作用。


所以总结一下,它返回选择(就像所有chainable d3方法一样),但它不修改实际检查的值。

根据文档- https://github.com/mbostock/d3/wiki/Selections

如果指定了value,则将指定名称的属性设置为所有选定元素上的指定值。

但是根据当前的代码,如果指定的值是undefined

,则不会发生这种情况。