开发者

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. But does it need the assignment to be evalu开发者_开发百科ated in the if statement?


No, you can't.

document.getElementById('fb0'), as the function name already says, returns the html element with has the id equal to fb0. After that you are accessing the attribute 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.


Not really; if getElementById('fb0') doesn't return anything your page will get an error, and in the first case it wouldn't.


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". The second version is ok if you don't remove the "fb0" element from the DOM at some point.


That would fail if document.getElementById('fb0') were not to exist. document.getElementById('fb0').onclick wouldn't mean much in that case.


If you do a lot of DOM selection by ID, make a shortened version of that method:

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;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜