获取选定选项并返回的问题

我对js中的返回值有疑问。我需要归还它,因为我想用它


 var rusiavimas = selectedServices();

所以,我的函数看起来像这样。


   function selectedServices()

    {

         var selectedServices = [];

        $('.common_change').change(function(){

        selectedServices = $(this).val();

        alert(selectedServices);

    

        

    });

        

      return selectedServices;

    

    }

我的 HTML 代码


              <select name="rusiavimas" class="common_change" id="cars">

                  <option value="none" selected disabled hidden> 

     Pasirinkite variantą 

  </option>  

          <option value="naujausi">Naujausi viršuje</option>

          <option value="pigiausi" >Pigiausi viršuje</option>

          <option value="brangiausi">Brangiausi viršuje</option>


            </select>

然后我选择该选项,在警报函数中我得到了正确的值,但在我的返回中,它没有返回它。


冉冉说
浏览 55回答 2
2回答

莫回无

您的代码包含很多问题,我尝试在下面修复它们你的JS脚本总是返回一个空数组,因为当你调用该函数时,var rusiavimas = selectedServices();内部.change函数不会运行并且不会更改数组的值var selectedServices = [];&nbsp; &nbsp; &nbsp; &nbsp; $('.common_change').change(function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectedServices.push($(this).val());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(selectedServices.length > 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("selected service: " + selectedServices.toString());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(selectedServices);&nbsp; &nbsp; &nbsp; &nbsp; });<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><select name="rusiavimas" class="common_change" id="cars">&nbsp; &nbsp; &nbsp; &nbsp; <option value="none" selected disabled hidden>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Pasirinkite variantą&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; </option>&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <option value="naujausi">Naujausi viršuje</option>&nbsp; &nbsp; &nbsp; &nbsp; <option value="pigiausi" >Pigiausi viršuje</option>&nbsp; &nbsp; &nbsp; &nbsp; <option value="brangiausi">Brangiausi viršuje</option>&nbsp; &nbsp; </select>

拉丁的传说

每次更改数组后,它都会为数组提供最后一个公共值。正如评论所说,最好的方法是使用selectedSerices.push($(this).val());&nbsp;您也可以使用深层复制,但在您的情况下不太建议这样做selectedSerices = [...selectedSerices, $(this).val()]。我想这会对你有帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript