三元运算符不改变 backgroundColor
ternary operator does not change backgroundColor
我正在尝试在输入为空时设置背景,并在输入为空时保持此值
function emptyto(element){
return element.value == '' ? element.style.backgroundColor = "#ccc" : element.val()
}
你的作业放错地方了:
function emptyto(element){
return element.style.backgroundColor = element.value == '' ? "#ccc" : element.val();
// ----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
另外:DOM 个元素没有 val
方法。您要么想在两个地方都使用 value
:
function emptyto(element){
return element.style.backgroundColor = element.value == '' ? "#ccc" : element.value;
// ----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
或者,如果您使用 jQuery,包装元素并在两个地方使用 val
(连同 css
):
function emptyto(element){
var $el = $(element);
return $el.css("backgroundColor", $el.val() == '' ? "#ccc" : $el.val());
}
实际上,由于 ''
是一个 falsy 值,我们可以使用 curiously-powerful ||
operator1 来简化那:
function emptyto(element){
return element.style.backgroundColor = element.value || "#ccc";
}
1(这是我贫血的小博客上的 post。)
我正在尝试在输入为空时设置背景,并在输入为空时保持此值
function emptyto(element){
return element.value == '' ? element.style.backgroundColor = "#ccc" : element.val()
}
你的作业放错地方了:
function emptyto(element){
return element.style.backgroundColor = element.value == '' ? "#ccc" : element.val();
// ----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
另外:DOM 个元素没有 val
方法。您要么想在两个地方都使用 value
:
function emptyto(element){
return element.style.backgroundColor = element.value == '' ? "#ccc" : element.value;
// ----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
或者,如果您使用 jQuery,包装元素并在两个地方使用 val
(连同 css
):
function emptyto(element){
var $el = $(element);
return $el.css("backgroundColor", $el.val() == '' ? "#ccc" : $el.val());
}
实际上,由于 ''
是一个 falsy 值,我们可以使用 curiously-powerful ||
operator1 来简化那:
function emptyto(element){
return element.style.backgroundColor = element.value || "#ccc";
}
1(这是我贫血的小博客上的 post。)