如何在 Javascript 中将元素 ID 作为参数或参数传递

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

How To pass Element Id In Javascript As Argument or parameter

javascript

提问by Shaurya Srivastava

how it is possible to get element from the id of input element and pass it as parameter to java script function.

如何从输入元素的 id 中获取元素并将其作为参数传递给 java 脚本函数。

 <html>
 <body>
 <input type="text" id="name">
 <input type="button" onclick="call(id_of_input_type_text)" value="Click 
  me">
 <script>
 var call(id_of_input_type_text) = function(){
 var x = document.getElementById(id_of_input_type_text).value;
 alert(x);
 }
 </script>
 </body>
</html>

Sir/Mam I want to use single function like validation and get there value by pass id in the function so please help me regarding this problem

先生/妈妈我想使用像验证这样的单一函数并通过函数中的传递 id 获得值所以请帮助我解决这个问题

采纳答案by Pranit Jha

Use the same function with different arguments for each call. Like you can use:

每次调用使用具有不同参数的相同函数。就像你可以使用:

<input type="button" onclick="call('name')" value="Click Me">

And it will alert the value of input field with id 'name'.

并且它会用 id 'name' 提醒输入字段的值。

Hope this helps.

希望这可以帮助。

回答by Jurij Jazdanov

Option 1 (from your question):

选项1(来自您的问题):

Note you can use call('name')in this case.

请注意,您可以call('name')在这种情况下使用。

var call = function(id){
  var x = document.getElementById(id).value;
  alert(x);
}
<input type="text" id="name">
<input type="button" onclick="call(document.getElementById('name').id)" value="Click me">

Option 2 (send the element, so you won't need to get it in the function):

选项 2(发送元素,因此您不需要在函数中获取它):

var call = function(elem){
  var x = elem.value;
  alert(x);
}
<input type="text" id="name">
<input type="button" onclick="call(document.getElementById('name'))" value="Click me">

回答by Sujith

You can use the below code as reference:

您可以使用以下代码作为参考:

<body>
 <input type="text" id="name">
 <input type="button" onClick="call('name')" value="Click me" id="btnOne">

 
 <script type="text/javascript">
var call = function(elementId)
{
 var valueOfInput = document.getElementById(elementId).value
    alert(valueOfInput);
}
</script>
 </body>