Javascript 使用多个此选项进行多个选择

Javascript 使用多个此选项进行多个选择,javascript,jquery,Javascript,Jquery,需要关于Jquery多重选择的帮助 这是密码 $.each(($("#reciprocitationAgreement option:selected:not([disabled]), #reciprocitationAgreement input")), function() { $(this).text(); }); 有两种类型的元素通过每个循环。 1-选择(选项)-从选项元素获取文本 2-输入字段-从输入字段获取值 有2个选定的元素。 是否有方法将同一代码块指向$(此选项).t

需要关于Jquery多重选择的帮助

这是密码

$.each(($("#reciprocitationAgreement option:selected:not([disabled]), #reciprocitationAgreement input")), function() {
     $(this).text();
});
有两种类型的元素通过每个循环。 1-选择(选项)-从选项元素获取文本 2-输入字段-从输入字段获取值

有2个选定的元素。
是否有方法将同一代码块指向
$(此选项).text()
$(这是输入).val()

在查找两种类型的输入时将代码移到函数中

 $.each(($("#reciprocitationAgreement option:selected:not([disabled])")), function() {
         doSomething($(this).text())
     });

 $.each(($("#reciprocitationAgreement input")), function() {
         doSomething($(this).val())
     });

这很简单,你可以在同一个函数中完成,你不需要两个函数。只需检查元素的标记名
是否为
INPUT
,然后进行相应操作:

$.each(($("#reciprocitationAgreement option:selected:not([disabled]), #reciprocitationAgreement input")), function() {
     if (this.tagName == 'INPUT') {
         $(this).val(); // ...
     } else {
         $(this).text(); // ...
     }  
 });

jsfiddle

您还可以创建一个JQuery扩展方法,如果您决定添加不同的类型,该方法将允许您在将来扩展这个方法。它还具有在许多地方使用的优点,只需一行就可以调用它,方法是说
$(“selectorgoesher”).getValue()


这是一把小提琴:

哼。。。如果您不想做两件完全不同的事情,我认为将选择器分成两个不同的选择器不是一个坏主意。标记名是什么意思?标记名是html元素标记的名称,如“DIV”或“a”或“SPAN”等。
$(function() {
  var data = [];
    $.each([ $("#reciprocitationAgreement option:selected:not([disabled])").text(), $("#reciprocitationAgreement input").val() ], function(k, v) {
       data.push(v);
      // do stuff with `data` , and / or ,
      // do stuff with `v`
      console.log(data);
      $("body").append(v);
    });
});
$.fn.getValue = function () {
    var returnValue = "";
    switch ($(this)[0].nodeName) {
        case "INPUT":
            returnValue = $(this).val();
            break;
        case "OPTION":
            returnValue = $(this).text();
            break;
        default:
            returnValue = $(this)[0];
            break;
    } // end switch
    return returnValue;
};
$(function () {
    $("#clickMe").click(function (e) {
        $("#reciprocitationAgreement option:selected:not([disabled]), #reciprocitationAgreement input").each(function () {
            console.log($(this).getValue());
        });
    });
});