欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript初級(jí)教程(第五課續(xù))

 更新時(shí)間:2007年04月05日 00:00:00   作者:  

    嘗試這個(gè)例子并閱讀下面的注釋:

    My favorite animal is ...

   

    注釋一個(gè)比較復(fù)雜的JavaScript程序。首先,我們看看表單本身:

    <form name="the_form">
        <select name="choose_category" onChange="swapOptions(window.document.the_form.choose_category.options[selectedIndex].text);">
            <option selected>Dogs</option>
            <option>Fish</option>
            <option>Birds</option>
        </select>

        <select name="the_examples" multiple>
            <option>poodle</option>
            <option>puli</option>
            <option>greyhound</option>
        </select>
    </form>

    該表單有兩個(gè)元素:一個(gè)下拉選單和一個(gè)列表選單。下列選單的處理器調(diào)用函數(shù)swapOptions()。該函數(shù)在首部已經(jīng)
作了定義,其參數(shù)為- 被選的動(dòng)物種類。

    首部中我首先定義的幾個(gè)數(shù)組:

    var dogs = new Array("poodle","puli","greyhound");

    var fish = new Array("trout", "mackerel", "bass");

    var birds = new Array("robin", "hummingbird", "crow");

    注意這些數(shù)組的命名和下拉選單中的命名一致。很快你就會(huì)明白為什么?,F(xiàn)在我們看看當(dāng)下拉選單被改變時(shí)被調(diào)用的函數(shù):

    function swapOptions(the_array_name)
    {
        var numbers_select = window.document.the_form.the_examples;
        var the_array = eval(the_array_name);
        setOptionText(window.document.the_form.the_examples, the_array);
    }

    該函數(shù)的定義包括一個(gè)參數(shù):the_array_name。如果打開(kāi)下拉選單并選擇"Fish" ,則the_array_name就等同于字符串"Fish"。

    函數(shù)主體中第1行包括一個(gè)變量用于引用第2個(gè)表單元素:列表選單。

    第2行引入一個(gè)新概念:eval()。eval()比較奇特,我們留在以后的課程中講解。第2行命令的這些結(jié)果是變量the_array將等同于前面所定義的數(shù)組之一。如果the_array_name是"Fish",the_array則等同于Fish數(shù)組。如果你想了解這是怎么作的,請(qǐng)學(xué)習(xí)eval。

    第3行定義另一個(gè)函數(shù)setOptionText()。setOptionText()用于將the_array賦值給列表選單。以下為該函數(shù)內(nèi)容:

    function setOptionText(the_select, the_array)
    {
        for (loop=0; loop < the_select.options.length; loop++)
        {
            the_select.options[loop].text = the_array[loop];
        }
    }

    該函數(shù)有兩個(gè)參數(shù):對(duì)選單元素的引用和一個(gè)數(shù)組。第1行設(shè)立一個(gè)for循環(huán),由于循環(huán)所有的選單元素。注意選單元素的選項(xiàng)屬性是該選單所有選項(xiàng)組成的數(shù)組。因?yàn)樗且粋€(gè)數(shù)組,你可以用長(zhǎng)度(length)屬性發(fā)現(xiàn)數(shù)組的元素?cái)?shù)目。第1次循環(huán)時(shí),循環(huán)變量值是0。循環(huán)的主體值為:

the_select.options[0].text = the_array[0];

    如果你在下拉選單中選擇了"Fish",則the_array[0]就是"trout",所以該行命令將列表選單中的第1個(gè)選項(xiàng)改成"trout" 。下一次循環(huán)時(shí),循環(huán)等于1,并且列表選單中第2個(gè)選項(xiàng)則是 "mackerel" 。

    如果你理解了該例子,你對(duì)JavaScript的了解就比較深了。 

    初級(jí)教程到此結(jié)束,隨后要發(fā)布進(jìn)階教程,敬請(qǐng)關(guān)注。

相關(guān)文章

最新評(píng)論