JavaScript 将参数 this.value 传递给函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12576669/
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-23 10:45:10  来源:igfitidea点击:

JavaScript pass argument this.value to function

javascript

提问by Raj Adroit

Here is my javascript code, i want to pass current selected value of the option to my js function, in this code i used static number 6.

这是我的 javascript 代码,我想将选项的当前选定值传递给我的 js 函数,在此代码中我使用了静态数字 6。

<select name='project_name' class='required input_field' id='project_name' onchange="sendRequest('GET','getClientName.jsp?ProjectId=6')">
<option value=''>-- Select --</option>
<option value="1">Project 1</option>
<option value="2">Project 2</option>
<option value="3">Project 3</option>
</select>

help me to solve this...

帮我解决这个问题...

回答by Marc

Change the string 'getClientName.jsp?ProjectId=6'to

将字符串更改'getClientName.jsp?ProjectId=6'

'getClientName.jsp?ProjectId=' + this.options[this.selectedIndex].value)

or

或者

'getClientName.jsp?ProjectId=' + this.value)

but I think the first one is more browser compatible.

但我认为第一个更兼容浏览器。

回答by richoffrails

var selectBox = document.getElementById('project_name');
selectBox.addEventListener('change', function() { 
  sendRequest('GET', 'getClientName.jsp?ProjectId=' + this.value); 
});

回答by kannanrbk

It will help you to get the selected option value . Try this link http://jsfiddle.net/xyaaa/9/.

它将帮助您获得选定的选项值。试试这个链接http://jsfiddle.net/xyaaa/9/

<html>
     <head>
         <script>
          function getOption(t){
               var val;
                var options = t.options;
                for(var i=0,len=options.length;i<len;i++){
                     var option = options[i];
                     if(option.selected){
                         val = option.value;
                     }
                }
                return val;
            }
             function  sendRequest(method , url){
                   console.log(url);
             }
    </script>
    </head>
            <body>
                <select onchange="var x=getOption(this);sendRequest('GET','getClientName.jsp?ProjectId='+x)">
                    <option value="1">Project 1</option>
                    <option value="2">Project 2</option>
                    <option value="3">Project 3</option>
                </select>
    </body>
</html>