關於select標籤曾經踩過的幾個坑!

1.情景展現

  select標籤,是前端開發界面展現,常常須要用到一個標籤,看看下面的坑,你中招了嗎?javascript

2.坑區展現

踩坑一:option標籤沒有聲明value屬性;html

  沒有聲明value屬性前端

<select id="gender">
    <option>--請選擇--</option>
    <option>男</option>
    <option>女</option>
</select>

  使用jquery獲取到的默認選項的值爲:--請選擇--java

  聲明value屬性jquery

<select id="gender">
    <option value="">--請選擇--</option>
    <option value="male">男</option>
    <option value="female">女</option>
</select>

  獲取到的值爲:""瀏覽器

  也就是說若是你沒有未option標籤聲明value屬性,取值時,獲取的將是選中項的文本信息。工具

踩坑二:獲取select標籤選中項對應的文本展現信息;開發工具

<select id="gender">
    <option value="">--請選擇--</option>
    <option value="male" selected>男</option>
    <option value="female">女</option>
</select>

  如上述代碼展現,默認選中的是第二個選項:「男」,若是獲取這個選項對應的展現信息,而不是獲取其對應的value的值?spa

$('#gender').val();

  獲取的是:male,不是咱們想要的!htm

//jquery獲取方式1:
$('#gender :selected').html();
//jquery獲取方式2:
$('#gender option:selected').html();
//jquery獲取方式3:
$('#gender :selected').text();
//jquery獲取方式4:
$('#gender option:selected').text();
// javascript獲取
var selectTag = document.getElementById('gender');
var selectedIndex = selectTag.selectedIndex;
// js方式1
selectTag.options[selectedIndex].innerHTML;
// js方式2
selectTag.options[selectedIndex].innerText;

  獲取的都是:男,這纔是咱們想要的。

踩坑三:option標籤後面只能跟文本信息

  option標籤內不能嵌套其它標籤,只能嵌套文本。

  網頁源代碼:

  F12打開開發工具,查看代碼

  這說明:瀏覽器會自動將option標籤內的HTML標籤剔除,就算添加了也沒用!想經過添加標籤的方式來控制展現文本的樣式,沒法實現!

 

寫在最後

  哪位大佬如若發現文章存在紕漏之處或須要補充更多內容,歡迎留言!!!

 相關推薦:

相關文章
相關標籤/搜索