简体   繁体   English

将 JS 函数添加到内部 html 字段?

[英]Add JS function to inner html field?

Beginner JavaScript Practice.初级 JavaScript 练习。 I am creating a simple page where the user can input a number of minutes and it will return the hours and minutes.我正在创建一个简单的页面,用户可以在其中输入分钟数,它将返回小时和分钟。 Ex: 500 minutes = 8hrs 20mins例如:500 分钟 = 8 小时 20 分钟

I have an input field for the user to input a number of minutes (works perfectly fine on it's own)我有一个输入字段供用户输入分钟数(它自己工作得很好)

I have a function that takes the total number of minutes and returns the equivalent hours:minutes (works perfectly fine on it's own as well)我有一个函数,它需要总分钟数并返回等效的小时数:分钟数(它自己也能很好地工作)

The issue I'm having is connecting these two sections of code to work together.我遇到的问题是将这两部分代码连接起来一起工作。 So that the user may input a number and minutes, then run the function, and return the hours and minutes equivalent the the number of minutes they gave.这样用户就可以输入一个数字和分钟,然后运行该函数,并返回与他们给出的分钟数相等的小时和分钟。

Any help would ge greatly appreciated, As I mentioned: I am very new to JavaScript (:任何帮助将不胜感激,正如我提到的:我是 JavaScript 的新手(:

 let form = document.getElementById("form") form.addEventListener('submit', function(event) { event.preventDefault() // prevents form from auto-submitting let userMinutes = document.getElementById("minutes").value //.value = extract the value the user has inputted // console.log(userMinutes) }); // JavaScript function to convert minutes —> hours and minutes function timeConvert(n) { let num = n; let hours = num / 60; let rhours = Math.floor(hours); let minutes = (hours - rhours) * 60; let rminutes = Math.round(minutes); return num + " minutes =" + rhours + " hour(s) and " + rminutes + " minute(s)." console.log(timeConvert(n)); };
 <form id="form"> <input type="text" id="minutes" name="minutes" placeholder="minutes" required> <input type="submit" value="submit"> </form>

First, there's no need for a form here since you won't be submitting any form data anywhere.首先,这里不需要form ,因为您不会在任何地方提交任何表单数据。 And, because there's no need for a form , you won't use the submit event or preventDefault() either.而且,因为不需要form ,所以您也不会使用submit事件或preventDefault() Instead, you just need a regular button to trigger the operation.相反,您只需要一个常规button即可触发操作。

See additional comments inline below:请参阅下面的附加评论:

 // Get your element references once rather that every time the function runs // And, when you do get your references, just get a reference // to the element, not any property of the element // so that in case you need to access the element at some // future point in time, you don't have to query the document // for the same element again. let userMinues = document.getElementById("minutes"); let result = document.querySelector("#result"); // No need for a separate function to do the work. // Just do it in the click handler document.querySelector("input[type='button'").addEventListener('click', function(event) { let num = userMinues.value; let hours = num / 60; let rhours = Math.floor(hours); let minutes = (hours - rhours) * 60; let rminutes = Math.round(minutes); // Event handlers shouldn't return anything because // you have no place to return the value to. Instead // populate an empty element that serves as a placeholder // for the answer. Also, don't use.innerHTML when you // can avoid it because it has performance and security // implications. result.textContent = num + " minutes =" + rhours + " hour(s) and " + rminutes + " minute(s)." });
 <input type="text" id="minutes" name="minutes" placeholder="minutes" required> <input type="button" value="Go!"> <div id="result"></div>

Best practice is to separate your calculation/logic things from the rest.最佳做法是将您的计算/逻辑事物与其他事物分开。 Try to get a section of code to do ONE thing.尝试获取一段代码来做一件事。

I left your form as a form but it might also just be some elements with click handlers etc.我将您的表单保留为表单,但它也可能只是一些带有点击处理程序等的元素。

Here I converted your function to return an object, called that then used that object that was returned to show the values.在这里,我将您的函数转换为返回一个对象,调用该对象然后使用返回的对象来显示值。

The whole display part might also be placed in another function but I left that to you to do that as a learning exercise here.整个显示部分也可以放在另一个函数中,但我把它留给你作为学习练习来做。

 let form = document.getElementById("form"); form.addEventListener('submit', function(event) { event.preventDefault(); // prevents form from auto-submitting let userMinutes = document.getElementById("minutes").value; // just get an object with the values from a function then use them: let timeThings = timeConvert(userMinutes); /* can do this one of two ways: string or a template literal */ // const showMe = timeThings.entered + " minutes = " + timeThings.hours + " hour(s) and " + timeThings.minutes + " minute(s)."; /* using a template literal: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals */ const showMe = `${timeThings.entered} minutes = ${timeThings.hours} hour(s) and ${timeThings.minutes} minute(s).`; console.log(showMe); }); function timeConvert(minutesEntered) { let hours = minutesEntered / 60; let rhours = Math.floor(hours); let minutes = (hours - rhours) * 60; let rminutes = Math.round(minutes); return { entered: minutesEntered, minutes: rminutes, hours: rhours }; }
 <form id="form"> <input type="number" id="minutes" name="minutes" placeholder="minutes" required> <input type="submit" value="submit"> </form>

You are not calling timeConvert() from your event handler.您没有从事件处理程序中调用timeConvert() Also, you were trying to console.log after returning from timeConvert() which means that even if you called it, it wouldn't log anything.此外,您在从timeConvert()返回后尝试console.log ,这意味着即使您调用它,它也不会记录任何内容。

 let form = document.getElementById("form") form.addEventListener('submit', function(event) { event.preventDefault() // prevents form from auto-submitting let userMinutes = document.getElementById("minutes").value // THE FIX console.log(timeConvert(userMinutes)); }); function timeConvert(n) { let num = n; let hours = num / 60; let rhours = Math.floor(hours); let minutes = (hours - rhours) * 60; let rminutes = Math.round(minutes); return num + " minutes =" + rhours + " hour(s) and " + rminutes + " minute(s)." };
 <form id="form"> <input type="text" id="minutes" name="minutes" placeholder="minutes" required> <input type="submit" value="submit"> </form>

Simply use your function as an event handler which is a function that is invoked when a registered event is triggered.只需将您的函数用作事件处理程序,该函数是在触发已注册事件时调用的函数。 You can use the HTMLFormElement interface for terse syntax and solid control over all form controls within the <form> .您可以使用HTMLFormElement接口来获得简洁的语法和对<form>中所有表单控件的可靠控制。

Details are commented in example详细信息在示例中进行了注释

 // Reference <form> const form = document.forms.form; /** * Bind <form> to "submit" event * When "submit" event is triggered, * invoke event handler convertTime(event) */ form.addEventListener('submit', convertTime); /** * Event handler passes event object by default * Stop default "submit" behavior of <form> * * Reference all <input> and <output> within <form> * Reference <input> * Reference <output> * * Convert the value of <input> from String to Number * (Next 4 lines are calculations) * * Assign the value of <output> as a template literal with the * calculated values interpolated within. */ function convertTime(event) { event.preventDefault(); const io = this.elements; const dataMin = io.minutes; const dataRes = io.result; let min = parseInt(dataMin.value); let hrs = min / 60; let rhrs = Math.floor(hrs); let mins = (hrs - rhrs) * 60; let rmins = Math.round(mins); dataRes.value = `${min} minutes = ${rhrs} hour(s) and ${rmins} minute(s).` };
 :root { font: 300 2ch/1.15 "Segoe UI" } input, output { display: block; min-height: 1.15rem; margin: 0.5rem 0; font: inherit; }
 <form id="form"> <.-- Use [type="number"] instead of [type="text"] --> <input id="minutes" name="data" type="number" placeholder="Minutes..." required> <!-- Use an output element to display results --> <output id="result" name="data"></output> <input type="submit"> </form>

There you go给你

<input id="minutes" type="number">
<button onclick="calc()">calc</button>
<div id="result"></div>

<script>
    function timeConvert(n) {
        let num = n;
        
        let hours = num / 60;
        let rhours = Math.floor(hours);
        
        let minutes = (hours - rhours) * 60;
        let rminutes = Math.round(minutes);
        
        
        return num + " minutes =" + rhours + " hour(s) and " + rminutes + " minute(s)."
    }
    
    function calc() {
      const result = timeConvert(parseInt(document.querySelector('#minutes').value))
      
      document.querySelector('#result').innerHTML = result
    }
</script>

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

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