if(!parent[0] || parent[0].style.display !== 'none') {
console.log('1');
}
我试着在一行中完成这项工作,但在Firefox中失败了,因为它给出了类型错误,即parent is undefined。但在这里,我正在尝试检查,如果是,就执行if循环。所以我把它一分为二的唯一解决方案是:
if(!parent[0]) {
console.log('1');
return;
}
if(parent[0].style.display !== 'none') {
console.log('1');
}
我怎么才能排成一行呢?为什么第一个代码失败,并指出父对象是未定义的,我如何才能防止这种情况,并只执行内部的控制台日志。
发布于 2017-07-13 14:55:22
这应该可以完成以下工作:
if(parent[0] && parent[0].style.display !== 'none') {
console.log('1');
}
使用someVariable && condition
意味着定义了someVariable
并且满足了条件。
在我看来,最易读的代码是:
function doSomething() {
// if condition is not met we quit the function
if(parent[0] === undefined) {
return false;
}
// parent[0] is defined we proceed
// Perhaps other conditions that should quit the function
if(parent[0].style.display === 'none') {
return false;
}
// parent[0] is defined we proceed and all checks are done
// All your logic here
}
发布于 2017-07-13 14:55:19
将逻辑更改为&&
。
if(parent[0] && parent[0].style.display !== 'none') {
console.log('1');
}
发布于 2017-07-13 15:11:37
所以我建议你试试:
"style" in parent[0] ? parent[0].style.display == "none" ? console.log(1) : 0 : 0;
注意,如果display
属性不是由javascript操作设置的,它将不会反映所请求的属性的状态。你将得到一个空字符串。
https://stackoverflow.com/questions/45084255
复制相似问题