我正在写一些生产代码,我想知道它是否正确使用'this'将对象传递给函数,就像我在我的代码版本中所做的那样。通过文档ID获取对象是否“更安全”?JavaScript输入字段大写是安全的
<!-- Code on Teaching site -->
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
</body>
</html>
<!-- My Version of Code -->
<script>
function myFunction(obj) {
obj.value = obj.value.toUpperCase();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction(this)">
</body>
</html>
IMO我不通过'this'看到任何问题。 – evolutionxbox
我总是使用'this' - 它允许干净的泛型函数 –
您的方法更通用,这很好,但您仍然可以改进它。只需添加类并将其绑定即可。因此,每次不必调用此函数。在文本框中,您只需添加类。这使得你的代码更加清晰易读。 – nikunjM