English 中文(简体)
如何在 jQuery 的文本、 索引或值中将选中的元素放入下拉式?
原标题:How to put selected element in dropdown by text, index or value with jQuery?
  • 时间:2012-05-22 06:17:21
  •  标签:
  • jquery

我有一个带有此结构的选定元素 :

<div class="ddl">
    <select>
        <option selected value="select">Select</option>
        <option value="T">Toyota</option>
        <option value="P">Porsche</option>
        <option value="N">Nissan</option>
        <option value="V">Volkswagen</option>
    </select>
</div>

并且没有选择元素的代号来传递给 jQuery 选择器, 只是 div 的母类 。

我怎样才能用文字、索引或价值来将这些要素中的任何一个作为选定的要素呢?

最佳回答

与选择者互动的方式各有不同。

<强>Using jQuery 1.6 和上:

案文:

$( .ddl option:contains("Porsche") ).prop( selected , true);

按指数排列:

$( .ddl option:eq(1) ).prop( selected , true);

按数值 :

$( .ddl option[value="T"] ).prop( selected , true);

<强>,旧版本:

案文:

$( .ddl option:contains("Porsche") ).attr( selected ,  selected );

按指数排列:

$( .ddl option:eq(1) ).attr( selected ,  selected );

按数值 :

$( .ddl option[value="T"] ).attr( selected ,  selected );
问题回答

尝试此 :

例如(有价值的选定):

$(".ddl select").val("T");
$(document).ready(function(){
$( div.ddl >select option:selected ).text(); //for getting text
$( div.ddl >select option:selected ).val(); //value
$( div.ddl >select option ).each(function(){ //looping
alert($(this).val());
});

});
$(".ddl select").attr("value","T");

$(.ddl> select ) 应该工作, 这是等级 ddl 和 & gt; 的 div 和 & gt; 告诉 jQuery 找到该类的直接子子。 不过要注意以等级 ddl 多于一个 ddiv 。





相关问题
getGridParam is not a function

The HTML: <a href="javascript:void(0)" id="m1">Get Selected id s</a> The Function: jQuery("#m1").click( function() { var s; s = jQuery("#list4").getGridParam( selarrrow )...

selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

jQuery cycle page with links

I am using the cycle plugin with pager functionality like this : $j( #homebox ) .cycle({ fx: fade , speed: fast , timeout: 9000, pager: #home-thumbs , ...

jquery ui dialog opens only once

I have a button that opens a dialog when clicked. The dialog displays a div that was hidden After I close the dialog by clicking the X icon, the dialog can t be opened again.

jConfirm with this existing code

I need help to use jConfirm with this existing code (php & Jquery & jAlert). function logout() { if (confirm("Do you really want to logout?")) window.location.href = "logout.php"; } ...

Wrap text after particular symbol with jQuery

What I m trying to do, is wrap text into div inside ll tag. It wouldn t be a problem, but I need to wrap text that appears particularly after "-" (minus) including "minus" itself. This is my html: &...

热门标签