Today took part in a code review activity, read a colleague's writing code, feel satisfied with the current function implementation, but in the long run, both from the code reuse point of view and maintenance is very poor. Let's see what the requirements are. The requirement is to show and hide a text box by selecting different options from the drop-down box. This is how the colleague wrote:
Code 1
<select name= "select" Onchange= "Disinput (This)" > <option value= "1" >1</option> < Option value= "2" >2</option> </select><input type= "text" id= "text" name= "text" style= "" value= " "/> <script type=" text/javascript "> function disinput (obj) { if (obj.value==2) { document.getElementById ("text"). style.display= "None"; } Else{document.getelementbyid ("text"). style.display= "";} } </script>
This writing should be all JS beginners are accustomed to thinking, according to the need to write a method to achieve the function. But I think if there is a similar requirement on another page, then it is not necessary to rewrite this method again, which day if the user asked to select option 1 in the text box to display the XX content, select 2 to show the other content, it is not all the pages have to be re-changed, can have a better way. This time can consider using CSS, of course, external CSS, here I wrote an example is to put the CSS in the page file, if the actual operation is definitely placed in the external CSS.
Code 2
Code 2 is more concise and, more importantly, it's good for code reuse and future maintainability. It is recommended that you consider the implementation of the code in terms of reuse and maintainability.
jquery uses CSS for displaying and hiding DOM elements