将用户HTML输入作为javascript函数参数传递

时间:2019-09-30 23:42:26

标签: javascript html function arguments substitution

我有这行javascript:

stave.addClef("treble").addTimeSignature("4/4");

根据用户在HTML文档中输入的内容,我想将“ 4/4”更改为“ 3/4”,或用户提出的任何其他分数。进行此条件替换的最简单方法是什么?

谢谢, 纳库尔

2 个答案:

答案 0 :(得分:1)

这是一个允许用户上下切换数字输入的选项:

<input type="number" id="fraction-1"/>
<input type="number" id="fraction-2"/>

Current Signature:
<div id="current-sig"></div>

然后在您的JavaScript中...


// Get the select form element
const FRACT_1 = 'fract-1'
const FRACT_2 = 'fract-2'
const fract1 = document.querySelector(`#${FRACT_1}`)
const fract2 = document.querySelector(`#${FRACT_2}`)
const currentSigDiv = document.querySelector('#current-sig')

let currentSignature = '4/4'

const changeSignatureByFraction = ({target}) => {
    if(target.id === FRACT_1)) {
        currentSignature = `${target.value}${currentSignature.substring(1)}`
        stave.addClef("treble").addTimeSignature(currentSignature)
        currentSigDiv.innerHTML = currentSignature
    } else {
        currentSignature = `${currentSignature.slice(0, -1)}${target.value}`
        stave.addClef("treble").addTimeSignature(currentSignature)
        currentSigDiv.innerHTML = currentSignature
    }

}

// Listen for a change event
fract1.addEventListener('change', changeSignatureByFraction)
fract2.addEventListener('change', changeSignatureByFraction)

currentSigDiv.innerHTML = currentSignature

答案 1 :(得分:0)

创建一个包含可能分数的下拉列表。 将其值查询到变量中。 将变量作为addTimeSignature()方法的参数传递。

HTML:

<select id="TimeSignatureSelect">
    <option value='1/4'>1/4</option>
    <option value='2/4'>2/4</option>
    <option value='3/4'>3/4</option>
    <option value='4/4'>4/4</option>
</select>

JS:

const timeSig = document.getElementByID('TimeSignatureSelect').value;
stave.addClef("treble").addTimeSignature(timeSig);