jquery操作select的一些基本方法總結

來源:互聯網
上載者:User

標籤:io   使用   ar   c   on   cti   html   r   new   

T1 >>> 建立一個新的select
var $newSelect = $("<select id=\"sel\" name=\"s_name\"></select>"); // 注意轉義\


T2 >>> 建立一個新的option
var $option = $("<option value=\"value\">1</option>");


T3 >>> 將option添加進數組 options
方式一:
$newSelect.append($option);
方式二:
$newSelect.append("<option value=\"value\">1</option>"); // 添加到 option 序列最後
方式三:
$newSelect.prepend("<option value=\"value\">1</option>"); // 添加到 option 序列最前
// 不支援option索引值溢出添加新的option

T4 >>> 將select添加到頁面
$newSelect.appendTo(‘body‘);
$newSelect.appendTo($(‘body‘));
$(‘body‘).append($newSelect);

// append() 和 appendTo() 方法執行的任務相同。
// 不同之處在於:內容和選取器的位置,以及 append() 能夠使用函數來附加內容。
$(selector).append(function(index,html))


T5 >>> 清除select的option選項
$("#sel option[value=‘1‘]").remove(); // 移除 value 值為 1 的 option
$("#sel option[index=2]").remove(); // 移除索引為 2 的 option
$("#sel option[text=‘_txt‘]").remove(); // 移除 text 值為 _txt 的 option
$("#sel option:last").remove(); // 移除最後的 option
$("#sel option:selected").remove(); // 移除selected選中的 option

T6 >>> 修改select的option選項

// 選中項的 text 值
newSelect.find(‘option:selected‘).text();

// 選中項的Value值
$newSelect.val()
$newSelect.find(‘option:selected‘).val();
$(‘select[name="s_name"]‘).find(‘option:selected‘).val();

// 任意項的 text val 值
$newSelect.find(‘option‘).eq(index).text();
$newSelect.find(‘option‘).eq(index).val();

$newSelect.children(‘option‘).eq(index).text();
$newSelect.children(‘option‘).eq(index).val();

$("#sel option[value=‘1‘]").text();
$("#sel option[value=‘1‘]").val();

$("#sel option[index=2]").text();
$("#sel option[index=2]").val();

$("#sel option[text=‘_txt‘]").text();
$("#sel option[text=‘_txt‘]").val();

// 輸出 option 序列的所有 text 值。
$newSelect.text()

// 輸出 select 被選中的索引值 。
$("#sel").get(0).selectedIndex; // get(0) 將jquery對象轉化為DOM形式。
$("#sel option:selected").index()

// 擷取 option 的長度值
$("#sel option").length
$newSelect.find(‘option‘).length
$newSelect.children(‘option‘).length


>>> 整個流程
<script>
var $newSelect = $("<select id=\"sel\"></select>");
var $option = $("<option value=\"1\">1</option>");
$(‘body‘).append($newSelect);
$newSelect.append($option);
</script>


註:有時候用到的jquery和Dom元素的一些轉換方式:
$(this)[0]
$(this).get(0)
$(this).toArray()[0];
以上3種寫法等價

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.