Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

javascript - 使用jQuery更改下拉列表的选定值(Change the selected value of a drop-down list with jQuery)

I have a drop-down list with known values. (我有一个带有已知值的下拉列表。) What I'm trying to do is set the drop down list to a particular value that I know exists using jQuery. (我正在尝试将下拉列表设置为使用jQuery知道的特定值。) Using regular JavaScript, I would do something like: (使用常规JavaScript,我会做类似的事情:)

ddl = document.getElementById("ID of element goes here");
ddl.value = 2; // 2 being the value I want to set it too.

However, I need to do this with jQuery, because I'm using a CSS class for my selector (stupid ASP.NET client ids...). (但是,我需要使用jQuery,因为我在选择器中使用了CSS类(愚蠢的ASP.NET客户端ID ...)。)

Here are a few things I've tried: (这是我尝试过的一些方法:)

$("._statusDDL").val(2); // Doesn't find 2 as a value.
$("._statusDDL").children("option").val(2) // Also failed.

How can I do it with jQuery? (如何使用jQuery?)

Update (更新资料)

So as it turns out, I had it right the first time with: (事实证明,我第一次做对了:)

$("._statusDDL").val(2);

When I put an alert just above it works fine, but when I remove the alert and let it run at full speed, I get the error (当我在上面放一个警报时,它可以正常工作,但是当我删除警报并使它以全速运行时,我得到了错误)

Could not set the selected property. (无法设置所选属性。) Invalid Index (无效索引)

I'm not sure if it's a bug with jQuery or Internet Explorer 6 (I'm guessing Internet Explorer 6), but it's terribly annoying. (我不确定这是不是jQuery或Internet Explorer 6的错误(我猜是Internet Explorer 6),但这非常令人讨厌。)

  ask by phairoh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

jQuery's documentation states: (jQuery的文档指出:)

[jQuery.val] checks, or selects , all the radio buttons, checkboxes, and select options that match the set of values. ([jQuery.val] 选中选择所有单选按钮,复选框,并选择与值集匹配的选项。)

This behavior is in jQuery versions 1.2 and above. (jQuery 1.2及更高版本中具有此行为。)

You most likely want this: (您最可能希望这样做:)

$("._statusDDL").val('2');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...