gpt4 book ai didi

javascript - d3 选择 .attr、.property 等 setter 方法在值未定义时的行为

转载 作者:行者123 更新时间:2023-11-27 23:58:28 24 4
gpt4 key购买 nike

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

它应该被视为假值,从而将 checked 属性设置为 false/removed,还是应该将其视为无值,从而像调用 一样。 property("checked"), setter/getter ?

最佳答案

属性方法

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 元素原型(prototype)链的上一层),因此它实际上什么也没做。

<小时/>

总而言之,它返回选择(就像所有可链接的 d3 方法一样),但它不会修改实际检查的值。

<小时/>

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

If value is specified, sets the property with the specified name to the specified value on all selected elements.

但根据当前代码,如果指定值未定义,则不会发生这种情况

关于javascript - d3 选择 .attr、.property 等 setter 方法在值未定义时的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32048014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com