简体   繁体   English

我可以减少这个 Javascript 代码吗?

[英]Can I reduce this Javascript code?

Can I reduce我可以减少吗

function n()
  {
  var a; 
  if(a = document.getElementById('fb0')) 
    {
    a.onclick = i0;
    document.getElementById('fb1').onclick = i1;
    }
  }

to

function n()
  {
  if(document.getElementById('fb0').onclick = i0) 
    {
    document.getElementById('fb1').onclick = i1;
    }
  }

I don't have a debugger right now.我现在没有调试器。 I know that document.getElementById('fb0') returns a value because the first snippet works fine.我知道document.getElementById('fb0')返回一个值,因为第一个片段工作正常。 But does it need the assignment to be evaluated in the if statement?但它是否需要在 if 语句中评估赋值?

Not really;并不真地; if getElementById('fb0') doesn't return anything your page will get an error, and in the first case it wouldn't.如果getElementById('fb0')没有返回任何内容,您的页面就会出错,而在第一种情况下不会。

To check if "document.getElementById('fb0')" returns an element or null, the second version don't do it and an error will be throw if there is no element with id "fb0".要检查“document.getElementById('fb0')”是否返回一个元素或 null,第二个版本不要这样做,如果没有 id 为“fb0”的元素将抛出错误。 The second version is ok if you don't remove the "fb0" element from the DOM at some point.如果您在某些时候不从 DOM 中删除“fb0”元素,则第二个版本是可以的。

No, you can't.不,你不能。

document.getElementById('fb0') , as the function name already says, returns the html element with has the id equal to fb0 . document.getElementById('fb0') ,正如 function 名称已经说过的那样,返回 id 等于fb0html element After that you are accessing the attribute onclick .之后,您将访问属性onclick But it the get fails it will break the script.但如果获取失败,它将破坏脚本。

On the first scenario you test if the assignment works, if does it means the element exists and will only execute if it exists.在第一个场景中,您测试分配是否有效,如果它是否意味着元素存在并且只有在它存在时才会执行。

Those are different behaviors.这些是不同的行为。

That would fail if document.getElementById('fb0') were not to exist.如果document.getElementById('fb0')不存在,那将失败。 document.getElementById('fb0').onclick wouldn't mean much in that case. document.getElementById('fb0').onclick在这种情况下意义不大。

If you do a lot of DOM selection by ID, make a shortened version of that method:如果您通过 ID 进行大量 DOM 选择,请制作该方法的简化版本:

function byId( id ) { return document.getElementById(id); };

function n() {
  var a; 
  if(a = byId('fb0')) {
    a.onclick = i0;
    byId('fb1').onclick = i1;
  }
}

In this case, doing the assignment inside the condition doesn't save you any characters.在这种情况下,在条件内进行赋值不会为您节省任何字符。 It's the same length to do it with the declaration.声明的长度相同。

function byId( id ) { return document.getElementById(id); };

function n() {
  var a = byId('fb0'); 
  if(a) {
    a.onclick = i0;
    byId('fb1').onclick = i1;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM