开发者

Which js function is more appropriate for industrial standards?

I have two JavaScript programs开发者_如何学Go, one I have used in my old company and another one I just came across in a site. Today, I noticed that my colleagues have used both these standards in the program and before finalizing the product, we have to change everything to one standard code.

<script type="text/javascript">
   // Reference the textbox
   var txt = document.getElementById("<%=txtName.ClientID%>");

   // If the textbox was found, call its focus function
   if (txt != null)
      txt.focus();
</script> 

or

<script type="text/javascript">
   // Reference the textbox and call its focus function
   var txt = $("#txtName");

   txt.focus();
</script> 

If you are in such a situation, which one will you suggest and why ?


First one is plain JS, second one uses jQuery wrapping. If you have adopted jQuery as JS framework, the second option is better :). 2nd in this particular case is better because you don't have to care about testing if that variable is null or not (you are calling the focus function of a jQuery element, so it will take care about checking whether the element is on the DOM or not)


If you are working in a team txtName.ClientID could have a meaning that's more clear to your colleagues. Having to plough through many lines of code from my colleagues on a daily base, I would go for that.
Or take the best of both worlds and use something like: $("#<%=txtName.ClientID%>").focus()


The second one uses jquery, so it is dependant on that libary, but it is much readable. You could even write it shorter: $("#txtName").focus();

The first one is faster, but in the big picture this difference won't matter much, but it is easier to write and read code with jQuery.


As stecb said, the first one is plain JavaScript code, and the second is some sort of JS library (most likely jQuery). There is no right or wrong approach here, even though it would make sense to use the library across the whole project if you are loading it, which you obviously are. Potential performance gains from using plain JavaScript are negligible for basic usage on modern systems.

You should check if all urls / pages load the JS library, sometimes developers only load certain libraries on some pages, which would prevent you from using the library unless you included it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜