jquery 操作 select 預設選擇第一個元素

來源:互聯網
上載者:User

標籤:code   開啟   pre   utf-8   meta   bsp   onclick   頁面   第一個   

  問題:點擊按鈕設定select元素的預設選項。

  首先,有個環境,並引入jquery。

<!DOCTYPE html><html>    <head>        <meta charset=‘utf-8‘>        <script src=‘jquery-1.11.3.js‘></script>    </head>    <body>        <select id=‘s1‘ class=‘selector‘>            <option>1</option>            <option>2</option>            <option>3</option>            <option>4</option>        </select>                <select id=‘s2‘ class=‘selector‘>            <option>1</option>            <option>2</option>            <option>3</option>            <option>4</option>        </select>                <button onclick=‘resetValue()‘>click me to reset select value</button>        <script>            function resetValue () {            }        </script>    </body></html>

  接下來就要寫方法了,其實思路很好懂,使用 jquery 也很 easy 來實現:

  1、首先找到 select 元素,這裡我們給他一個 class 方便尋找。

var selectArr = $(‘.selector‘);

  2、找到這個 select 數組後,通過 jquery 的 each() 方法進行遍曆。第一個參數是下標位置,第二個參數是數組元素。

selectArr.each(function (i, j) {})

  3、對於每個select元素,我們需要做的是對其下的第一個 option 標籤進行設定選中

var options = $(j).find("option");options.first().attr("selected", true);

  4、開啟頁面,點點,咦,怎麼有點問題?哈,在設定選中前,要將之前選中項置 false。這裡我就全 false 一下方便。

options.attr("selected", false);

  完成啦!

  最終方法內容:

function resetValue () {    $(‘.selector‘).each(function (i, j) {        var options = $(j).find("option");        options.attr("selected", false);        options.first().attr("selected", true);    })}

   再來簡化下(將之前選中項置 false):

function resetValue () {    $(‘.selector‘).each(function (i, j) {        $(j).find("option:selected").attr("selected", false);        $(j).find("option").first().attr("selected", true);    })}

 

jquery 操作 select 預設選擇第一個元素

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.