我试图从一个输入框中获取输入,使用getGetOrdinal()函数将其转换为序数形式,然后使用getO()函数在第二个框中显示它,我想知道是否必须将输入框的值转换为整数由getGetOrdinal()函数使用。
function getGetOrdinal(n) {
var s=["th","st","nd","rd"],
v=n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
function getO() {
var inOne = document.getElementById("one").value;//*takes value
var result = getGetOrdinal("inOne");//* passes inOne into getGetOrdinal
var inTwo = document.getElementById("two");
inTwo.textContent = result;//*displays ordinal number in second box
}
<form>
<form>
<input id="one" type="number"><!-- first input box-->
<button type="button" onlick="getO()">submit</button><!-- should turn value of firsdt input box into ordinal number-->
<input type="number" id="two"><!-- should display ordinal number-->
</form>
最佳答案
1)您应该将getGetOrdinal("inOne")
更改为getGetOrdinal(inOne)
。您没有传递变量,而是包含inOne
的字符串。
2)同样,您需要更改的是设置第二个输入的value
属性而不是textContent
3)最后,请确保argument
函数的getGetOrdinal
是一个数字
function getGetOrdinal(n) {
n = +n; // This is for numbers like '5e2'
if(isNaN(n)) { // <-- 3
throw new Error('You should provide a number as the argument for getGetOrdinal function')
}
var s = ["th","st","nd","rd"],
v = n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
function getO() {
var inOne = document.getElementById("one").value;
var result = getGetOrdinal(inOne); // <-- 1
var inTwo = document.getElementById("two");
inTwo.value = result; // <-- 2
}