Javascript функция не работает oninput () или onchange () - PullRequest
1 голос
/ 07 октября 2019

Я создаю простое приложение, которое конвертирует Ether в различные его единицы. Я настроил его так, чтобы при вводе числа в поле ввода выполнялась моя функция конвертации и отображалась конверсия в нужную единицу (которую можно выбрать в раскрывающемся списке).

Проблема, с которой я столкнулся, заключается в том, что функция запускается только при загрузке страницы. После этого, независимо от того, что я ввожу, отображаемое значение конверсии не изменится по умолчанию, даже если у меня установлена ​​функция конвертации для запуска oninput, onchange и onclick по отношению к HTML-элементам, которые принимаютданные.

Я убедился, что мой скрипт запускается ПОСЛЕ полной загрузки страницы, поместив его в самый конец HTML-файла, но это никак не помогло.

HTML:

<div id="conversions">
           <p>
                 <input type="number" id="etherAmount" value="2"> ether to <select id="etherUnits">
                    <option id="wei" value="wei">Wei</option>
                    <option id="mwei" value="mwei">Mwei/Lovelace/Picoether</option>
                    <option id="gwei" value="gwei">Gwei/Shannon/Nanoether/Nano</option>
                    <option id="szabo" value="szabo">Szabo/Microether/Micro</option>
                    <option id="finney" value="finney">Finney/Milliether/Milli</option>
                    <option id="ether" value="ether">Ether</option>
                    <option id="kether" value="kether">Kether/Grand</option>
                    <option id="mether" value="mether">Mether</option>
                    <option id="gether" value="gether">Gether</option>
                    <option id="tether" value="tether">Tether</option>
                    <input type="submit" value="Convert" id="convert">
                </select>
            </p>

        </div>
        <div id="resultsContainer">
            <p id="results"></p>
        </div>

JS:

const converter = require("ethereumjs-units")
let etherUnits = document.getElementById("etherUnits")
let etherAmount = document.getElementById("etherAmount")
let convertButton = document.getElementById("convert")
let results = document.getElementById("results")


etherUnits.oninput = convert()
etherAmount.onchange = convert()
etherAmount.oninput = convert()
convertButton.onclick = convert()
//Takes value of ether input box and converts it
function convert() {

    //value of "convert to" box
    let etherUnitVal = etherUnits.options[etherUnits.selectedIndex].value
    results.innerHTML = converter.lazyConvert(etherAmount.value.toString() + " eth", etherUnitVal)
}

Ответы [ 2 ]

1 голос
/ 07 октября 2019

Я полагаю, что ваша проблема здесь в том, что вы вместо назначения функции, которая будет выполняться этим обработчиком событий, вы выполняете функцию, и, поскольку convert() не возвращает функцию, обработчики ничего не сделают

Попробуйте

etherUnits.oninput = convert

0 голосов
/ 07 октября 2019

Вы можете попробовать это, это работает.

HTML:

<div id="conversions">
    <p>
        <input type="number" id="etherAmount" value="2" onchange="covert()"> ether to <select id="etherUnits"
            oninput="convert()">
            <option id="wei" value="wei">Wei</option>
            <option id="mwei" value="mwei">Mwei/Lovelace/Picoether</option>
            <option id="gwei" value="gwei">Gwei/Shannon/Nanoether/Nano</option>
            <option id="szabo" value="szabo">Szabo/Microether/Micro</option>
            <option id="finney" value="finney">Finney/Milliether/Milli</option>
            <option id="ether" value="ether">Ether</option>
            <option id="kether" value="kether">Kether/Grand</option>
            <option id="mether" value="mether">Mether</option>
            <option id="gether" value="gether">Gether</option>
            <option id="tether" value="tether">Tether</option>
            <input type="submit" value="Convert" id="convert" onclick="convert()">
        </select>
    </p>

</div>
<div id="resultsContainer">
    <p id="results"></p>
</div>

JS:

    const converter = require("ethereumjs-units")
    let etherUnits = document.getElementById("etherUnits")
    let etherAmount = document.getElementById("etherAmount")
    let convertButton = document.getElementById("convert")
    let results = document.getElementById("results")

    //Takes value of ether input box and converts it
    function convert() {

        //value of "convert to" box
        let etherUnitVal = etherUnits.options[etherUnits.selectedIndex].value
        results.innerHTML = converter.lazyConvert(etherAmount.value.toString() + " eth", etherUnitVal)
    }

Я просто изменил и добавил на входе, замена на соответствующие блокивместо в js

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...