简体   繁体   English

在输入 oninput 中调用 javascript 方法作为回调

[英]Calling javascript method as callback in input oninput

 class ClassWien { constructor(t, w) { this.t = t; this.w = w; } read_t() { let t = document.getElementById("wien_t").value; this.t = parseFloat(t); console.log(this); } read_w() { let w = document.getElementById("wien_w").value; this.w = parseFloat(w); console.log(this); } calculate() { this.w = 2.9e-3 / this.t; document.getElementById("wien_w").value = this.w; console.log(this); } } let wien = new ClassWien(0, 0); window.onload = function() { document.getElementById("wien_t").addEventListener("input", wien.read_t); document.getElementById("wien_w").addEventListener("input", wien.read_w); document.getElementById("wien_solve").addEventListener("click", wien.calculate); }
 @charset "utf-8"; body { font: 100% Arial, Helvetica, sans-serif; background: #123c69; text-align: left; color: #000; } /* Define page layout */.container { width: 800px; background: #fff; padding: 15px; margin: 0 auto; border: none; font-family: Arial, Helvetica, sans-serif; }.indented { padding: 15px; margin: 0; }.indent-left { padding: 15px 0 15px 180px; margin: 0; } h1, h4 { padding: 0; margin: 0; } h2 { padding-bottom: 0; margin: 0; } p, h4 { padding: 15px 0 0 15px; margin: 0; } ol { padding-left: 45px; margin: 0; }
 <,DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="style.css"> <title>Astronomy Equations</title> <script src=calculations.js></script> </head> <body> <div class="container"> <form name="wien" class="indented"> <h2>Wien's Law</h2> <p>This equation describes the relationship between the <b>temperature</b> of an object emitting a thermal spectrum and the <b>wavelength</b> of the brightest part of the emitted spectrum:</p> <table align="center" class="indent-left"> <tbody> <tr> <td>temperature:</td> <td colspan="2"></td> <td><input type="text" name="wien_t" id="wien_t"></td> <td>Kelvins</td> </tr> <tr> <td>wavelength:</td> <td colspan="2"></td> <td><input type="text" name="wien_w" id="wien_w"></td> <td>meters</td> </tr> <tr> <td></td> <td><input type="button" value="Solve" id="wien_solve"></td> <td><input type="button" value="Clear"></td> <td colspan="2"></td> </tr> </tbody> </table> </form> </div> </body> </html>

I'm writing a webpage that will solve an equation when the user enters all but one of the input values for a given equation.我正在编写一个网页,当用户输入给定方程的除一个输入值之外的所有值时,它将求解一个方程。 I've created a javascript class with methods for reading the numerical values from the html input fields and then solving for the missing value.我创建了一个 javascript class 方法,用于从 html 输入字段中读取数值,然后求解缺失值。

I can use a standalone function as the callback, such as:我可以使用独立的 function 作为回调,例如:

<input oninput="read_t()">

But when I try to call the same function defined as a class method, such as:但是当我尝试调用相同的 function 定义为 class 方法时,例如:

<input oninput="equation.read_t()">

I get the following error:我收到以下错误:

Uncaught TypeError: equation.read_t is not a function
    at HTMLInputElement.oninput

I have created an instance of the class called "equation".我创建了一个名为“方程式”的 class 实例。 So I'm not sure if I'm calling the method incorrectly within the input tag or this kind of thing simply isn't allowed in html/javascript.所以我不确定我是否在输入标记中错误地调用了该方法,或者在 html/javascript 中根本不允许这种事情。

I'm not sure I need to include the callback as part of the class or just make it a standalone function: that was working.我不确定我是否需要将回调作为 class 的一部分包含在内,或者只是使其成为独立的 function:这是有效的。 It just seems cleaner to include the callback within the class.在 class 中包含回调似乎更简洁。 I'd like to know if instance methods can be callbacks or if I've made some other mistake.我想知道实例方法是否可以是回调,或者我是否犯了其他错误。

Any help is appreciated!任何帮助表示赞赏!

Update : I have added a trimmed-down version of the page for inspection.更新:我添加了一个精简版的页面以供检查。 I'm not sure what I changed in the last few hours of work, but the instance methods now execute when text is entered into the input fields.我不确定在过去几个小时的工作中我做了什么更改,但是现在在输入字段中输入文本时会执行实例方法。 However, I have discovered that the input text is not assigned to the properties of instance wien as intended.但是,我发现输入文本未按预期分配给实例wien的属性。 This puzzled me for a while since assignment should be a pretty basic operation.这让我困惑了一段时间,因为赋值应该是一个非常基本的操作。 Then I accidentally discovered that this in the read_t and read_w and calculate methods are referring to the input elements wien_t , wien_w , and wien_solve , not to the wien class instance.然后我偶然发现read_tread_wcalculate方法中的this是指输入元素wien_twien_wwien_solve ,而不是wien class 实例。 I guess I don't understand how this behaves in this case.我想我不明白在这种情况下this是如何表现的。 I would have expected these instance methods would refer to the instance itself -- since they are defined as methods in ClassWien -- and not to the DOM elements they've been added to as EventListeners.我原以为这些实例方法会引用实例本身——因为它们被定义为 ClassWien 中的方法——而不是它们作为 EventListeners 添加到的 DOM 元素。

maybe you need to call it using objectName.functionName() not className.functionName()也许您需要使用 objectName.functionName() 而不是 className.functionName() 来调用它

for instance例如

below format gave me the same error equation.read is not a function下面的格式给了我同样的错误方程。读取不是 function

<input type="text" id="myInput" oninput="equation.read()">

but below format works fine但以下格式工作正常

<input type="text" id="myInput" oninput="equationObject.read()">

this is the code I wrote in my script tag这是我在脚本标签中写的代码

class equation{
    read(){
        var x = document.getElementById("myInput").value;
        console.log(x);
    }

}

equationObject = new equation();

I tried replicating your problem and it seems that using static will enable you to call the function in the class and not using it will lead to the error you are experiencing.我尝试复制您的问题,似乎使用 static 将使您能够在 class 中调用 function 而不使用它会导致您遇到的错误。

Html Html

<input type="text" oninput="equation.read_t()"/>

Javascript Javascript

class equation {
    constructor() {

    }
    static read_t() {
        console.log("Hello");
    }
}

Static methods let you call methods on the class itself. Static 方法允许您调用 class 本身的方法。

Event handling using method bindings is typically better practice than oninput .使用方法绑定的事件处理通常比oninput更好。

See the Mozilla Docs: https://developer.mozilla.org/en-US/docs/Web/API/EventListener请参阅 Mozilla 文档: https://developer.mozilla.org/en-US/docs/Web/API/EventListener

Here's a quick summary:这是一个快速的总结:

  1. Set id attribute.设置 id 属性。
  2. Initialize equation class.初始化方程 class。
  3. Bind method to input event.将方法绑定到输入事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM