我得到一个像这样的HTML字符串。我想获得所选的值,在本例中为AN
:
<SELECT id=ddl_Freq name=ddl_Freq><OPTION selected value=AN>Annually</OPTION> <OPTION value=BM>Bi-Monthly</OPTION> <OPTION value=MO>Monthly</OPTION> <OPTION value=OT>One Time</OPTION> <OPTION value=QT>Quarterly</OPTION> <OPTION value=WE>Weekly</OPTION></SELECT>
格式化时如下所示:
<SELECT id=ddl_Freq name=ddl_Freq>
<OPTION selected value=AN>Annually</OPTION>
<OPTION value=BM>Bi-Monthly</OPTION>
<OPTION value=MO>Monthly</OPTION>
<OPTION value=OT>One Time</OPTION>
<OPTION value=QT>Quarterly</OPTION>
<OPTION value=WE>Weekly</OPTION>
</SELECT>
我尝试了这两种方法,但我没有成功。
DdlHtml = document.createElement('select');
DdlHtml.innerHTML = RawDdlString;
item = DdlHtml.options[DdlHtml.selectedIndex].value;
此操作失败,因为该字符串已包含<SELECT>
和</SELECT>
标记。
DdlHtml2 = $.parseHTML(RawDdlString);
item = DdlHtml2.options[DdlHtml2.selectedIndex].value;
这也不起作用,因为DdlHtml2.options
未定义。
如何在Javascript或jQuery中解析包含HTML下拉列表的HTML的字符串?
答案 0 :(得分:3)
将字符串换行到jQuery选择器:
$(function() {
var $select = $("<SELECT id=ddl_Freq name=ddl_Freq><OPTION selected value=AN>Annually</OPTION> <OPTION value=BM>Bi-Monthly</OPTION> <OPTION value=MO>Monthly</OPTION> <OPTION value=OT>One Time</OPTION> <OPTION value=QT>Quarterly</OPTION> <OPTION value=WE>Weekly</OPTION></SELECT");
console.log($select.val());
});
Here是一个示例小提琴
答案 1 :(得分:0)
使用jQuery
$( '#ddl_Freq')。VAL()
答案 2 :(得分:0)
没有jQuery,
<SELECT id=ddl_Freq name=ddl_Freq>
<OPTION selected value=AN>Annually</OPTION>
<OPTION value=BM>Bi-Monthly</OPTION>
<OPTION value=MO>Monthly</OPTION>
<OPTION value=OT>One Time</OPTION>
<OPTION value=QT>Quarterly</OPTION>
<OPTION value=WE>Weekly</OPTION>
</SELECT>
var x = document.getElementById("ddl_Freq");
x.options[x.selectedIndex].value;
Output:
"AN"
链接到jsbin片段:
http://jsbin.com/omuxow/1/edit