当我将值作为函数的参数时,
像这样,
<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>
效果不错。
它向我展示了 v 的值(value)。
但是,当我将类作为参数时,
像这样,
<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()
returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either benull
or""
(the empty string);
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>
className
gets and sets the value of theclass
attribute of the specified element.
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>
或者:即使您可以传递this 对象,以便您可以根据需要访问函数内的所有属性:
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>
关于javascript - 如何将类作为函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53465084/