天天看点

【js:片断】jQuery 设置 select 下拉框的选中状态

<mce:script type="text/javascript"><!--

function change(objID, newValue) {

var obj = $("#" + objID);

if (!obj) {

alert("对象为空,执行返回!");

return;

}

var options = obj.find("option");

options.each(function (i) {

if ($(this).text() === newValue) {

$(this).attr("selected", true); -- 也可用 obj.get(0).selectedIndex = i; 替代

});

// --></mce:script>

注意事项:

  1、对象相等行判断,使用 === 而不是 == ,js 引擎执行两个相等符号时,会自动进行类型转换。比较 "1"==1  与 "1"===1 即可知道结果

  2、以上代码需要引用 jQuery 库。本人out了,最近才知道该库的强大

  3、学会使用 $, .find(), .attr 的使用

  4、使用替代品 obj.get(0).selectedIndex = i; 时,没有完全理解其意思,obj.get(0) 获得的是什么东东,为何它有 selectedIndex 属性呢?

继续阅读