简体   繁体   English

JavaScript代码在chrome上有效,在IE和Firefox上无效

[英]JavaScript code works on chrome, doesn't work on IE and firefox

I created this script for educational reasons in pure JS. 出于教育原因,我在纯JS中创建了此脚本。 It adds sorting to tables (when a header is clicked). 它将对表添加排序(单击标题时)。 I decided that it's quite useful and tried to use it in my project. 我认为它非常有用,并尝试在我的项目中使用它。 It works fine on Google Chrome (I used this browser when I was creating the script), but doesn't on IE and Firefox. 它在Google Chrome(在创建脚本时使用了该浏览器)上运行良好,但在IE和Firefox上却无法使用。 Can you help me? 你能帮助我吗?

alert("Remember to add LoadSetup function to window.onload event and to remove this alert.\nAlso remember that table you want to sort must have class 'sortable' and an unique id.\nThe table must be build properly using <thead> and <tbody> tags.")


function addLoadEvent(func) {
// Dobra funkcja która radzi sobie z dodawaniem nowych funkcji do zdażenia window.onload
    var oldonload = window.onload;
    if (typeof window.onload != 'function') window.onload = func;
    else {
        window.onload = function() {
            if (oldonload) oldonload();
            func();
        }
    }
}

window.onload = LoadSetup;

function LoadSetup()
{
    //find sortable tables and set sorting state to 0 (not sorted)  
    tables = document.getElementsByTagName("table");
    tablesStates = new Array(tables.length);

    for(var i=0;i<tables.length;i++){
        tableName = tables[i].getAttribute("id");
        if(hasClass(tables[i], "sortable") && tableName != null){
            tablesStates[tableName] = new Array();

            thead = tables[i].getElementsByTagName("thead")[0];
            header = thead.getElementsByTagName("tr")[0].getElementsByTagName("th");

            for(var j=0; j<header.length; j++){
                if(!hasClass(header[j], 'notsortable')){
                    tablesStates[tableName][header[j].innerHTML] = 0;
                    header[j].removeAttribute("onclick");
                    header[j].setAttribute("onclick", "sortTable('"+tableName+"', '"+header[j].innerHTML+"')");
                }
            }
        }
    }
}

function hasClass(ele, cls)
{
    return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

String.prototype.capitalize = function() {
// fajna funkcja
    return this.charAt(0).toUpperCase() + this.slice(1);
}
String.prototype.capitalizeAll = function() {
// fajna funkcja
    result = '';
    for(var i=0; i< this.length;i++)
        result += this.charAt(i).toUpperCase();
    return result;
}

function prepareStringForCmp(s){
    en = ['a','c','e','l','n','o','s','z','z','A','C','E','L','N','O','S','Z','Z'];
    pl = ['ą','ć','ę','ł','ń','ó','ś','ź','ż','Ą','Ć','Ę','Ł','Ń','Ó','Ś','Ź','Ż'];

    for(var i=0;i<pl.length;i++){
        regex = new RegExp(pl[i],"g");
        s = s.replace(regex,en[i]);
    }
    return s.capitalizeAll();
}

function cmpStr(a, b){
    //a=prepareStringForCmp(a);
    //b=prepareStringForCmp(b);
    if(a == b)return 0;
    else if(a > b) return 1;
    else return -1;
}
function cmpStrRev(a, b){return cmpStr(b, a);}

function cmpNum(a, b){ return a - b;}
function cmpNumRev(a, b){return cmpNum(b, a);}

function cmp(a,b,type,asc)
{
// returns -1 if a < b ---- in ascending mode ( asc=true)
// returns 1 is a > b ---- in ascending mode ( asc=true)
// returns 0 if a == b

    if(type == "number"){
        if(asc == true) return cmpNum(a,b);
        else return cmpNumRev(a,b);
    }
    else if(type == "date"){
        if(asc == true) return 0;
        else return 0;
    }
    else{
        if(asc == true) return cmpStr(a,b);
        else return cmpStrRev(a,b);

    }
}

/////////////////////////////////////////////////////////////
// Bubble Sort

function bubbleSortTable(tab, col, type, asc) {
    for(var i=0; i < tab.length; i++){
        for(var j=0; j< tab.length-1; j++){
            if(cmp(tab[j].getElementsByTagName("td")[col].innerText, tab[j+1].getElementsByTagName("td")[col].innerText, type, asc) > 0)
            {
                buf = tab[j].innerHTML;
                tab[j].innerHTML = tab[j+1].innerHTML;
                tab[j+1].innerHTML = buf;
            }
        }
    }
}

/////////////////////////////////////////////////////////////
// Quick Sort

function partitionTable(l, r, A, col, type, asc)
{
    x = A[l].getElementsByTagName("td")[col].innerText;
    i = l-1;
    j = r+1;
    while(true){
        while(true){
            j = j-1;
            if(cmp(A[j].getElementsByTagName("td")[col].innerText, x, type, asc) <= 0) break;
        }
        while(true){
            i = i+1;
            if(cmp(A[i].getElementsByTagName("td")[col].innerText, x, type, asc) >= 0) break;
        }

        if(i<j){
            buf = A[i].innerHTML;
            A[i].innerHTML = A[j].innerHTML;
            A[j].innerHTML = buf;
        }
        else return j;
    }

}

function qsortTable(l, r, A, col, type, asc)
{
//qsort(tablica, 0, tablica.lenght -1);
    if(l<r){
        q = partitionTable(l, r, A, col, type, asc);
        qsortTable(l, q, A, col, type, asc);
        qsortTable(q+1, r, A, col, type, asc);
    }
}

/////////////////////////////////////////////////////////////

function sortTable(id, colName){
// sorts table
// returns true if sorting done; otherwise false
// works for strings and numbers


    if(tablesStates[id][colName] >= 0) asc = true;
    else asc = false;

    tab = document.getElementById(id);
    thead = tab.getElementsByTagName("thead")[0];
    header = thead.getElementsByTagName("tr")[0].getElementsByTagName("th");
    tbody = tab.getElementsByTagName("tbody")[0];
    rows = tbody.getElementsByTagName("tr");

    col = -1;
    for(var i=0; i < header.length; i++){
        if(header[i].innerHTML == colName){
            col = i;
            colType = header[i].getAttribute("class");      
            break;
        }
    }
    if(col == -1) return false;

    // demanded header found

    bubbleSortTable(rows, col, colType, asc);
    //qsortTable(0, rows.length-1,rows, col, colType, asc);
    if(tablesStates[id][colName] >= 0) tablesStates[id][colName] = -1;
    else tablesStates[id][colName] = 1;
}

And also a simple html for this: 还有一个简单的html:

<!DOCTYPE html PUBLIC 
"-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" 
xml:lang="pl" lang="pl">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="sortTable.js"></script>
    <link rel="stylesheet" type="text/css" href="x.css" />
</head>
<body>
<div id="content_box">

<table class="sortable"  id="tabela1">
<thead>
    <tr><th>name</th><th class="number">age</th><th>city</th></tr>
</thead>
<tbody>
    <tr> <td>Jan</td> <td>21</td> <td>Gdańsk</td> </tr>
    <tr> <td>Andrzej</td> <td>17</td> <td>Warszawa</td> </tr>
    <tr> <td>Paweł</td> <td>112</td> <td>toruń</td> </tr>
    <tr> <td>Mateusz</td> <td>43</td> <td>Łomża</td> </tr>
        <tr> <td>ADAM</td> <td>21</td> <td>Gdańsk</td> </tr>
    <tr> <td>ŻANETA</td> <td>17</td> <td>Warszawa</td> </tr>
    <tr> <td>Paweł</td> <td>112</td> <td>toruń</td> </tr>
    <tr> <td>LEON</td> <td>43</td> <td>Łomża</td> </tr>
        <tr> <td>Jan</td> <td>21</td> <td>Gdańsk</td> </tr>
    <tr> <td>Andrzej</td> <td>17</td> <td>Warszawa</td> </tr>
    <tr> <td>FRYDERYK</td> <td>112</td> <td>toruń</td> </tr>
    <tr> <td>Mateusz</td> <td>43</td> <td>Łomża</td> </tr>
        <tr> <td>Jan</td> <td>21</td> <td>Gdańsk</td> </tr>
    <tr> <td>BALBINA</td> <td>17</td> <td>Warszawa</td> </tr>
    <tr> <td>ADAM</td> <td>112</td> <td>toruń</td> </tr>
    <tr> <td>TERESA</td> <td>43</td> <td>Łomża</td> </tr>
</tbody>
</table>
</div>
</body>
</html>

More detailed description: 更详细的描述:

LoadSetup - works (and adds sorting functionality) When header is clicked it should do the sorting and it does on Chrome. LoadSetup-工作(并添加了排序功能)单击标题时,它应该进行排序,并且在Chrome上进行。 Than it goes like this: sortTable >> bubbleSortTable >> cmp in cmp(a,b,type,asc) a and b are 'undefined' in Firefox and IE and than the script somewhere breaks and nothing gets sorted. 比它看起来像这样:sortTable >> bubbleSortTable >> cmp(a,b,type,asc)a和b中的cmp在Firefox和IE中是“未定义”的,而且脚本在某处中断了,没有任何排序。

I'm not going through all your code, especially since your description is rather vague: "doesn't work" is obvious - you wouldn't ask here if everything works, so being a little more specific and trying to narrow the problem down (thus posting less code) is probably a good idea. 我不会遍历您的所有代码,尤其是因为您的描述相当模糊:“不起作用”很明显-您不会在这里询问一切是否正常,因此要更具体一点并尝试缩小问题范围(因此,发布更少的代码)可能是一个好主意。 But from the three second glance that I gave I see you're setting event handlers with setAttribute . 但是从我给我的三秒钟看,我看到您正在使用setAttribute设置事件处理程序。 Not a good idea (for example, see this post ). 这不是一个好主意(例如,请参阅这篇文章 )。 That doesn't work in some versions of IE (again, versions are something you didn't specify). 这在某些版本的IE中不起作用(同样,您未指定版本)。

To add one more thing: even doing elem.onclick = ... isn't really recommended. 再添加一件事:甚至不建议使用elem.onclick = ... It's the old HTML 4.0 method. 这是旧的HTML 4.0方法。 Using the DOM Event Model is recommended, ie ( addEventListener etc.). 建议使用DOM事件模型,即( addEventListener等)。 But then there are endless cross-browser issues, which is why there are js libraries. 但是,接着就出现了无休止的跨浏览器问题,这就是为什么有js库的原因。 As such, I suggest porting your code to jQuery or some other such library to make things truly portable. 因此,我建议将您的代码移植到jQuery或其他此类库中,以使事情真正可移植。

It's a good idea because otherwise you'll just end up reinventing the wheel, and probably not as well as years of experienced developers have already done. 这是一个好主意,因为否则您将不得不重新发明轮子,并且可能不及多年的经验丰富的开发人员所做的那样。 Moreover, you will probably add to this code and it will grow. 此外,您可能会添加到此代码中,并且它会不断增长。 js libraries used properly will help the scalability of the code. 正确使用js库将有助于代码的可伸缩性。

No, this isn't an answer to your question. 不,这不是您的问题的答案。 And if you're looking for a quick fix to the issue, this isn't it. 如果您正在寻找快速解决此问题的方法,那不是。 But I strongly feel that this advice, while harder (much harder) to implement in the short term, is your best bet if you want that code to be truly usable and maintainable. 但是我强烈认为,尽管在短期内很难(更难)实施此建议,但如果您希望该代码真正可用和可维护,则是最好的选择。

One problem is that you are using the innerText property which isn't supported in Firefox. 一个问题是您使用的是Firefox不支持的innerText属性。 See 'innerText' works in IE, but not in Firefox for (loads) of details. 有关详细信息,请参阅“ innerText”在IE中的工作原理,但不适用于Firefox

Edit: I tested your code in Firefox and the only change I made was from innerText to textContent and it worked. 编辑:我在Firefox中测试了您的代码,而我所做的唯一更改是从innerText到textContent,它起作用了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript不适用于Chrome和Firefox,但适用于IE - Javascript doesn't work on Chrome and Firefox, but works on IE JavaScript时钟可在Chrome上使用,但不适用于Firefox或IE - JavaScript clock works on Chrome but doesn't work with Firefox or IE Javascript 自动完成功能适用于 IE 和 Chrome,不适用于 Firefox - Javascript autocomplete works in IE and Chrome, doesn't work in Firefox 该Javascript在IE中不起作用,但在Chrome,Firefox和Opera中起作用 - This Javascript doesn't work in IE but works in Chrome, Firefox and Opera JS正则表达式代码不适用于Firefox,但适用于Chrome和IE - JS regex code doesn't work with firefox, but works on chrome and IE Javascript仅在IE Quirks,7和Chrome和Firefox中有效。 在IE 8或9标准中不起作用 - Javascript only works in IE Quirks, 7 and Chrome and Firefox. Doesn't work in IE 8 or 9 Standards EmberData unloadAll在IE8上不起作用。 适用于Chrome / FireFox - EmberData unloadAll doesn't work on IE8. Works on Chrome/FireFox .unbind(&#39;submit&#39;)。submit()在Chrome / IE中有效,但在Firefox中无效 - .unbind('submit').submit() works in Chrome/IE but doesn't work in Firefox jQuery模糊在Firefox和Chrome中不起作用,但在IE9中起作用 - Jquery blur doesn't work in Firefox and Chrome but works in IE9 Jquery / Javascript和Css条件在firefox和IE上不起作用。 它适用于Chrome - Jquery/Javascript and Css condition doesn't work on firefox and IE. It works on Chrome
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM