gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:50:34 25 4
gpt4 key购买 nike

如何从输入元素的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>

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

最佳答案

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

请注意,在这种情况下您可以使用 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">

选项 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">

关于javascript - 如何在 Javascript 中将元素 ID 作为参数或参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44195082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com