javascript - 降序表以及 JavaScript 中的升序

标签 javascript html sorting

所以我创建了一个动态 JavaScript 表,它与 HTML 一起创建一个英里到 KM 转换器。我的表当前运行升序,但我不确定如何让它运行降序,因为用户应该有这个选项。我相当确信 for 循环也是如此,但我想知道是否有人可以帮助我解决这个问题。

function milesConverterAsc(tagId, from, to){

var first = document.getElementById("Input1");
var second = document.getElementById("Input2");
from = parseInt(first.value);
to = parseInt(second.value);
var conv = document.getElementById(tagId);
var tab = document.createElement("table");
var bod = document.createElement("tbody");
var thed = document.createElement("thead");
tab.appendChild(thed);
tab.appendChild(bod);
var tr = document.createElement("tr");
thed.appendChild(tr);
var th = document.createElement("th");
tr.appendChild(th);
th.appendChild(document.createTextNode("Miles"));
th = document.createElement("th");
tr.appendChild(th);
th.appendChild(document.createTextNode("Kilometers"));
conv.appendChild(tab);

for(var i=from; i<=to; i++){
    tr = document.createElement("tr");
    if (i <= -1){
        alert("Value must be positive Integer");
        return false;
    }
    else if (i % 2 == 0)
        tr.setAttribute("class", "even");
    else
        tr.setAttribute("class", "odd");
    bod.appendChild(tr);
    td = document.createElement("td");
    tr.appendChild(td);
    td.appendChild(document.createTextNode(i));
    td = document.createElement("td");
    tr.appendChild(td);
    td.appendChild(document.createTextNode(mtk(i)));
}
function mtk(m) {
    outputOne = ((m * 1.6093)*10)/10;
    outputTwo = outputOne.toFixed(2);
    return outputTwo
}

编辑:这是我用来获取输入的 HTML 代码。

<form action="">
<p> ASCENDING ORDER</p>
</br></br>
    <textarea rows="1" name="Input1" id="Input1" cols="10"></textarea>
    <textarea rows="1" name="Input2" id="Input2" cols="10"></textarea>

</form>

希望你能帮帮我!这是升序码。

最佳答案

您在 for 循环中创建表格行。每行都基于 for 循环的索引变量。现在它总是按升序排列,假设从 < 到。要使其颠倒顺序,只需将 for 循环设置切换为:

for(var i=to; i>=from; i--)

A simple codepen to demonstrate

关于javascript - 降序表以及 JavaScript 中的升序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35139589/

相关文章:

javascript - 单击播放后如何加载视频?

javascript - 如何使用lodash向数组中的所有对象添加键值对

在 O(n) 中将 n 个数字从 0 排序到 n^m 的算法?其中 m 是常数

Javascript 通过 bool 属性对对象数组进行排序

javascript - 如何在不使用 lambda 函数的情况下将参数发送到 React 渲染组件中的处理程序事件?

javascript - 在 JavaScript 中将多组参数作为数组传递是否比多个函数调用更快?

javascript - jQuery Mobile - 移至下一页/上一页 - 单击后执行操作两次

javascript - 在 for 循环中带有 for 循环的函数两个变量都不能完全工作

html - 响应式网格是什么以及如何实现它

iphone - 如何使用 sortUsingFunction(或 sortUsingSelector)对包含数组的对象的 NSMutableArray 进行排序