<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    躺在沙灘上的小豬

    快樂(lè)的每一天

    #

    Javascript Best Practices

    URL: http://www.javascripttoolbox.com/bestpractices/

    Matt Kruse
    October 10, 2005
    Version 1.0

    Introduction

    This document will explain some important Javascript concepts and show the preferred way of handling common situations and problems. It should be read by anyone developing web applications and using javascript.

    Square Bracket Notation

    Objects properties in javascript can be accessed in two ways: Dot notation and Square bracket notation.

    Dot notation
    MyObject.property
    Square bracket notation
    MyObject["property"]

    With dot notation, the property name is hard-coded and cannot be changed at run-time. With bracket notation, the property name is a string which is evaluated to resolve the property name. The string can be hard-coded, or a variable, or even a function call which returns a string property name.

    If a property name is being generated at run-time, the bracket notation is required. For example, if you have properties "value1", "value2", and "value3", and want to access the property using a variable i=2:

    This Will Work
    MyObject["value"+i]

    This Will Not
    MyObject.value+

    For convenience and consistency, using square-bracket-notation instead of dot-notation is a good practice to get into.

    Referencing Forms And Form Elements

    The correct way to reference a form input element is:

    document.forms["formname"].elements["inputname"]

    All forms should have a name attribute. Referencing forms using indexes, such as document.forms[0] is bad practice.

    If you will be referencing multiple form elements within a function, it's best to make a reference to the form object first and store it in a variable.

    var theform = document.forms["mainForm"];
    theform.elements[
    "input1"].value="a"
    ;
    theform.elements[
    "input2"].value="b";

    Referencing Forms From Element Handlers

    When you are validating an input field using onChange or similar event handlers, it is always a good idea to pass a reference to the input element itself into the function. Every input element has a reference to the form object that it is contained in.

    <input type="text" name="address" onChange="validate(this)">
    function validate(input_obj) {
        
    // Reference another form element in the same form

        if (input_obj.form.elements["city"].value==""{
             alert(
    "Error"
    );    
             }

    }

    By passing a reference to the form element, and accessing its form property, you can write a function which does not contain a hard reference to any specific form name on the page.

    Problems With Concatenation

    In javascript, the + operator is used for both addition and concatenation. This can cause problems when adding up form field values, since Javascript is a non-typed language. Form field values will be treated as strings, and if you + them together, javascript will treat it as concatenation instead of addition.

    Problematic Example
    <form name="myform">
    <input type="text" name="val1" value="1">
    <input type="text" name="val2" value="2">
    </form>

    function total() {
        
    var theform = document.forms["myform"
    ];
        
    var total = theform.elements["val1"].value + theform.elements["val2"
    ].value;
        alert(total); 
    //
     This will alert "12", but what you wanted was 3!
      }

    To fix this problem, Javascript needs a hint to tell it to treat the values as numbers, rather than strings. Subtracting 0 from the value will force javascript to consider the value as a number, and then using the + operator on a number will perform addition, rather than concatenation.

    Fixed Example
    <form name="myform">
    <input type="text" name="val1" value="1">
    <input type="text" name="val2" value="2">
    </form>

    function total() {
        
    var theform = document.forms["myform"
    ];
        
    var total = (theform.elements["val1"].value-0+ theform.elements["val2"
    ].value;
        alert(total); 
    // This will alert 3

    }

    Using onClick in <A> tags

    When you want to trigger javascript code from an anchor tag, the onClick handler should be used. The javascript code that runs within the onClick handler needs to return true or false back to the tag itself. If it returns true, then the HREF of the anchor will be followed like a normal link. If it returns false, then the HREF will be ignored. This is why "return false;" is often included at the end of the code within an onClick handler.

    In this case, the "doSomething()" function will be called when the link is clicked, and then false will be returned. The href will never be followed for javascript-enabled browsers. However, if the browser does not have javascript enabled, the javascript_required.html file will be loaded, where you can inform your user that javascript is required. Often, links will just contain href="#" for the sake of simplicity, when you know for sure that your users will have javascript enabled. Otherwise, it's always a good idea to put a local fall-back page that will be loaded for users without it disabled.

    Sometimes, you want to conditionally follow a link. For example, if a user is navigating away from your form page and you first want to validate that nothing has changed. In this case, your onClick will call a function and it will return a value itself to say whether the link should be followed.

    In this case, the validate() function should always return either true or false. True if the user should be allowed to navigate back to the home page, or false if the link should not be followed. This example prompts the user for confirmation, then returns true or false, depending on if the user clicked OK or Cancel.

    These are all examples of things NOT to do. If you see code like this in your pages, it is not correct and should be fixed.

    Eval

    The eval() function in javascript is a way to run arbitrary code at run-time. In almost all cases, eval should never be used. If it exists in your page, there is almost always a more correct way to accomplish what you are doing. The rule is, "Eval is evil." Don't use it.

    Detecting Browser Versions

    Some code is written to detect browser versions and to take different action based on the user agent being used. This, in general, is a very bad practice.

    The better approach is to use feature detection. That is, before using any advanced feature that an older browser may not support, check to see if the function or property exists first, then use it. This is better than detecting the browser version specifically, and assuming that you know its capabilities. An in-depth article about this topic can be found at http://www.jibbering.com/faq/faq_notes/not_browser_detect.html if you want to really understand the concepts.

    Don't Use document.all

    document.all was introduced by Microsoft in IE and is not a standard javascript DOM feature. Although many newer browsers do support it to try to support poorly-written scripts that depend on it, many browsers do not.

    There is never a reason to use document.all in javascript except as a fall-back case when other methods are not supported.

    Only Use document.all As A Last Resort
    if (document.getElementById) {
        
    var obj = document.getElementById("myId"
    );
    }
    else if (document.all) {
        
    var obj = document.all("myId"
    );
    }

    The rules for using document.all are

    1. Always try other standard methods first
    2. Only fall back to using document.all as a last resort
    3. Only use it if you need IE 5.0 support or earlier
    4. Always check that it is supported with "if (document.all) { }" around the block where you use it.

    Getting And Setting Form Values

    The method used to get and set form values depends on the type of form element. A detailed explanation of how to correctly access form controls can be found at http://www.jibbering.com/faq/faq_notes/form_access.html.

    In general, it is a good practice to use generalized getInputValue() and setInputValue() functions to read and write values to form elements. This will make sure that it is always done correctly, and situations that otherwise might cause confusion and errors are handled correctly. For example, forms with only 1 radio button in a group, or multiple text inputs with the same name, or multi-select elements.

    The getInputValue() and setInputValue() functions are part of the validations.js library from the Javascript Toolbox. The most current version of these functions and other validation functions can be found at http://www.javascripttoolbox.com/validations/.

    Additional Resources

    The comp.lang.javascript FAQ has many common questions and answers about javascript. It is a great resource to check if you have what you think might be a FAQ.

    For general-purpose libraries and examples, see The Javascript Toolbox.

    If you want to really exploit the javascript language and use advanced techniques, read about Javascript Closures.



    end

    posted @ 2005-10-11 15:22 martin xus| 編輯 收藏

    Gmail & JavaMail.

         摘要: 雖然jakarta的commons email 簡(jiǎn)化了javamail的使用,但是遇到復(fù)雜一點(diǎn)的東東,我們還是需要重新拿起javamail來(lái),也許我們可以做.其實(shí)javamail也不是太復(fù)雜 o_o 下面是通過(guò)gmail發(fā)送郵件,因?yàn)間mail需要smtp驗(yàn)證,所有要額外的設(shè)定mail.smtp.auth 值為 true并且添加java.security.Security.addProvider(...  閱讀全文

    posted @ 2005-10-10 21:03 martin xus| 編輯 收藏

    [ZT]Hibernate和Spring的決裂以及Spring和EJB3之爭(zhēng)

    http://forum.javaeye.com/viewtopic.php?t=16363

    posted @ 2005-10-10 20:26 martin xus| 編輯 收藏

    javamail 一些資源..

    看到幾位朋友對(duì)這挺感興趣的,整理點(diǎn)資料放在這里共享一下.

    老本家
    http://java.sun.com/products/javamail/index.jsp

    developerworks 的教程 JavaMail API 基礎(chǔ)
    https://www6.software.ibm.com/developerworks/cn/education/java/j-javamail/tutorial/index.html
    本地下載

    JavaMail FAQ: 好東西
    http://java.sun.com/products/javamail/FAQ.html


    無(wú)中文困撓的使用JavaMail收取郵件
    http://www.javayou.com/showlog.jspe?log_id=372

    使用JavaMail的郵件發(fā)送組件
    http://www.javayou.com/showlog.jspe?log_id=136


    最后一個(gè)就是簡(jiǎn)化了javamail開(kāi)發(fā)的。
    Jakarta Commons Emails

    ---------------------------------------------------------------------------------
    以前寫(xiě)的一篇介紹:
    《簡(jiǎn)化JavaMail:小巧 Jakarta Commons-Email 簡(jiǎn)單教程

    順便再整理一下,朋友討論的關(guān)于一些jakarta commons email出現(xiàn)亂碼的問(wèn)題:

    一:通過(guò)SimpleEmail發(fā)送中文內(nèi)容出現(xiàn)亂碼的問(wèn)題
    SimpleEmail的代碼如下
     1public class SimpleEmail extends Email {
     2    
    /**
     3     * Set the content of the mail
     4
         *
     5     * @param
     msg A String.
     6     * @return
     An Email.
     7     * @throws
     EmailException see javax.mail.internet.MimeBodyPart
     8
         *                        for definitions
     9     * @since
     1.0
    10     */

    11    public Email setMsg(String msg) throws EmailException {
    12        if (EmailUtils.isEmpty(msg)) 
    {
    13            throw new EmailException("Invalid message supplied"
    );
    14        }

    15        setContent(msg, Email.TEXT_PLAIN);
    16        return this
    ;
    17    }

    18}

    只是采用默認(rèn)的,

    1public static final String TEXT_PLAIN = "text/plain";

    并沒(méi)有指定編碼。

    如果通過(guò)SimpleEmail發(fā)送,需要指定編碼:
    Water Ye@ITO 的說(shuō)明
     
    1email.setContent("測(cè)試郵件""text/plain;charset=GBK"); 

    二:關(guān)于附件中文名稱(chēng)亂碼的問(wèn)題:

    需使用MimeUtility

    原因是在MIME的相應(yīng)規(guī)范中(RFC2047等)說(shuō)明了附件標(biāo)題必須是US-ASCII字符, 所以在發(fā)送中文標(biāo)題的附件時(shí)需要編碼成US-ASCII字符, 有兩種編碼方式: B (BASE64), Q (Quoted-Printable), 這些方法在MimeUtility里
    都已經(jīng)做了封裝, 所以在發(fā)送附件時(shí)使用如下:

    1MimeUtility.encodeText(filename));


     1        EmailAttachment attachment = new EmailAttachment();
     2        attachment.setPath("c:\\測(cè)試.txt"
    );
     3
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
     4        attachment.setDescription("測(cè)試文件"
    );
     5        

     6           //
     7
            attachment.setName(MimeUtility.encodeText("測(cè)試文件.txt"));
     8

     9         MultiPartEmail email = new
     MultiPartEmail();
    10        email.setHostName("192.168.0.3"
    );
    11        email.setAuthentication("martin.xus""1234"
    );
    12        email.addTo("martin.xus@192.168.0.3""martin"
    );
    13        email.setFrom("martin.xus@192.168.0.3""martin"
    );
    14

    15        email.setSubject("測(cè)試帶附件"
    );
    16        email.setMsg("該郵件含附件"
    );
    17        //添加附件

    18        email.attach(attachment);
    19        //發(fā)送郵件

    20        email.send();


    end
    ---------------------------------------------------------------------------------

    我想這些資源已經(jīng)足夠 o_o

    你還想知道什么:)

    posted @ 2005-10-10 19:21 martin xus| 編輯 收藏

    Eclipse Plugin--A Ruby on Rails IDE:RadRails

    RadRails is an integrated development environment for the Ruby on Rails framework. The goal of this project is to enhance the rails development experience. RadRails seeks to make life simpler by providing rails developers with a single point to manage multiple projects, take advantage of source control and deploy their applications.


    當(dāng)前版本為0.2
    http://www.radrails.org/

    posted @ 2005-10-09 20:06 martin xus| 編輯 收藏

    僅列出標(biāo)題
    共28頁(yè): First 上一頁(yè) 18 19 20 21 22 23 24 25 26 下一頁(yè) Last 
    主站蜘蛛池模板: 在线播放亚洲精品| 亚洲欧洲国产成人精品| 亚洲毛片av日韩av无码| 亚洲中文字幕久久精品无码APP | 国产日本一线在线观看免费| 日本免费无遮挡吸乳视频电影| 亚洲av中文无码| 亚洲av网址在线观看| 亚洲日韩中文字幕一区| 亚洲成av人片在线看片| aⅴ免费在线观看| 一本久久综合亚洲鲁鲁五月天| 亚洲视频在线播放| 免费无遮挡无遮羞在线看| 亚洲免费视频播放| 亚洲中文字幕人成乱码| 免费久久人人爽人人爽av| 日本不卡在线观看免费v| 精品久久久久亚洲| 1000部夫妻午夜免费 | 国产精品美女久久久免费| 可以免费看黄的网站| 亚洲乱码日产精品一二三| 免费a级毛片大学生免费观看| 亚洲黄网在线观看| a级毛片毛片免费观看久潮| 免费在线一级毛片| 三年片免费高清版 | 国产精品久久永久免费| 亚洲国产成人片在线观看| 国产精品日本亚洲777| 久久亚洲国产精品五月天婷| 老司机免费午夜精品视频| 日韩成全视频观看免费观看高清| 成人亚洲国产精品久久| 亚洲AV色香蕉一区二区| 成年性羞羞视频免费观看无限| 亚洲日本国产精华液| 成人永久免费高清| 四虎国产成人永久精品免费| 亚洲精品WWW久久久久久|