开发者

How do I optimize this Javascript?

I tried to convert snippet 1 to snippet 2 but this did not work (the text fields did not clear). f3aa and f3bb are each text fields that I need to clea开发者_运维技巧r after a sumbit.

Snippet 1

var target=document.getElementById('f3aa');
target.value='';
var target=document.getElementById('f3bb');
target.value='';

Snippet 2

o1('f3aa')=o1('f3bb')='';

Snippet 3

function  o1(a)
  {
  document.getElementById(a);
  }


Assuming I've understood your question correctly, you were nearly there:

document.getElementById('f3aa').value = '';
document.getElementById('f3bb').value = '';

In your snippet 2, you are trying to assign an empty string to a DOM element, rather than the value property of that element.

In snippet 1, you assign a DOM element to the target variable, and then assign an empty string to the value property of the target variable. As target contains a DOM element, you assign that string to the value property of that element, which is equivalent to the code I have shown above.


You forgot to include the attribute names from your first snippet in your second:

document.getElementById('f3aa').value='';
document.getElementById('f3bb').value='';

(Note that this isn't really an "optimization" - there will be no noticeable difference in how quickly the two snippets run. Use whichever is more readable.)


X('f3aa').value = X('f3bb').value = '';

where X is your query-by-ID implementation.

Live demo: http://jsfiddle.net/zmr29/

(I wrote a X function in my demo, but I assume that you either use a library or have some other shorthand for DOM queries.)


I think it's illegal to use var to declare a variable more than once in the same scope.

This code is bad:

var test = true;
var test = false;

This code is good:

var test = true;
    test = false; // <-- no "var" keyword here
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜