我正在做我的数学游戏而且我有char(加号或减号)的问题。我怎么能在数字之前加上或减去呢?我需要检查输入的号码,我不想要情况例如" - 8-88"。问题出在输入按钮上,名称为"减去"。
<body onload="main_page();">
<form name="game">
<div style="float: left;" class="screen">
<input type="text" id="answer" value="" autofocus()>
</div>
<input type="button" value="-" onclick="game.answer.value += '-'" name="minus">
<input type="button" value="8" name="eight" onclick="game.answer.value += '8'" >
</form>
答案 0 :(得分:1)
您要附加-
而不是预先添加game.answer.value = -game.answer.value
。您可以通过仅取数值来切换减号,并将一元减号运算符应用于它:
<form name="game">
<div style="float: left;" class="screen">
<input type="text" id="answer" value="" autofocus()>
</div>
<input type="button" value="-" name="minus"
onclick="game.answer.value = -game.answer.value">
<input type="button" value="8" name="eight" onclick="game.answer.value += '8'" >
</form>
script
请考虑使用JavaScript的onclick
标记。 1}}在{{1}}属性中添加更多代码是不可取的。
答案 1 :(得分:0)
我想你想避免在数字前加几个符号,你希望你的数字总是显示它们是正数还是负数。要做到这一点,你必须将它们转换为字符串并检查它们是否已经有了&#39; +&#39;或者减去&#39; - &#39;。要删除不需要的字符,可以使用regexp:
const addPlus = (n) => `+${ n.toString().replace(/[+-]/g, '') }`;
const addMinus = (n) => `-${ n.toString().replace(/[+-]/g, '') }`;
您可以在此处查看一个有效的示例:https://jsfiddle.net/oniondomes/n7ytsdy4/