[英]How can I make a function that takes in a parameter and when executed, it alerts whatever you give the function?
[英]How can I give a class as a parameter to function?
当我将值作为参数来运行时,
像这样,
<html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(v) { console.log(v); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(value)"> </body> </html>
它运作良好。
它显示了我的价值。
但是,当我把课作为参数时,
像这样,
<html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(c) { console.log(c); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(class)"> </body> </html>
它给了我一个错误。
我想让它显示按钮的类选项“A”。
我该怎么做?
getAttribute()
返回元素上指定属性的值。 如果给定的属性不存在,则返回的值将为null
或""
(空字符串);
onclick="clicked(this.getAttribute('class'))"
<html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(c) { console.log(c); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(this.getAttribute('class'))"> </body> </html>
或者:使用Element.className
className
获取并设置指定元素的class
属性的值。
onclick="clicked(this.className)"
<html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(c) { console.log(c); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(this.className)"> </body> </html>
或者:即使您可以传递此对象,以便您可以根据需要访问函数内的所有属性:
onclick="clicked(this)"
<html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(c) { console.log(c.className); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(this)"> </body> </html>
这是您的解决方案。 使用DOM元素className。
<html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(c) { console.log(c); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(this.className)"> </body> </html>
你可以通过this
给函数,然后该函数将有机会获得所有的input
元素属性,其中之一是className
,但你也可以在访问任何其他属性,不改变调用机制
<html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(v) { console.log(v.className,v.value,v.type); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(this)"> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.