jQuery 获取上一个选择的下拉项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4041927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:33:43  来源:igfitidea点击:

get previous selected dropdown item

jquerybuttondrop-down-menu

提问by leora

i have the following code where i have a dropdown list (with class="addToList" and followed by a button (Class="addtoButton"):

我有以下代码,其中有一个下拉列表(带有 class=" addToList",后跟一个按钮(Class=" addtoButton"):

When i click on the button, i want to grab the current selected value and text from the previous dropdown list.

当我单击按钮时,我想从上一个下拉列表中获取当前选定的值和文本。

$(".addToPortalButton").live('click', function (e) {

// grab the previous dropdown list value and text here.

});

what is the easiest way to doing this using jquery.

使用 jquery 执行此操作的最简单方法是什么。

Here is the html:

这是html:

<select class="addToList" id="Teams" name="Teams">
     <option></option>
    <option value="49">Team 1</option>
    <option value="22">Team 2</option>
</select>
<input type='button' class="addToButton" value='Add to' />

<select class="addToList" id="Teams" name="Teams">
     <option></option>
    <option value="49">Team 1</option>
    <option value="22">Team 2</option>
</select>
<input type='button' class="addToButton" value='Add to' />

<select class="addToList" id="Teams" name="Teams">
     <option></option>
    <option value="49">Team 1</option>
    <option value="22">Team 2</option>
</select>
<input type='button' class="addToButton" value='Add to' />

采纳答案by Nick Craver

You can use .prev()or .prevAll()to get the <select>before like this:

您可以使用.prev().prevAll()来获得这样的<select>before :

Edit:for newer versions of jQuery where .live()has been deprecated, the new .on()syntax is:

编辑:对于.live()已弃用的较新版本的 jQuery ,新.on()语法为:

$(document).on('click', '.addToButton', function (e) {
  var sel = $(this).prevAll('.addToList:first'),
      val = sel.val(),
      text = sel.find(':selected').text();    
});

Older version:

旧版本:

$(".addToButton").live('click', function (e) {
  var sel = $(this).prevAll(".addToList:first"),
      val = sel.val(),
      text = sel.find(':selected').text();    
});

回答by lonesomeday

You can do this with the following code:

您可以使用以下代码执行此操作:

$(".addToButton").on('click', function (e) {

    var $el = $(this).prev().find('option:selected');

});

You can then use $el.val()and $el.text()to get the value and text respectively.

然后$el.val(),您可以使用和$el.text()分别获取值和文本。