开发者

Need help with the parseInt() function

How do I get the phrase number from the phrase object using the parseInt() function? I tried to create the function within the swapFE function in var phrasenum below but it did not work. I think my values are wrong. What should I put there instead? Any help would be greatly appreciated. Thanks in advance! The following is the french phrase number (1-10 or in JavaScript 0-9) and the french an english phrases to be used:

> var english=new Array();
english[0]="This hotel isn't far from the Eiffel Tower.";
english[1]="What time does the train arrive?";
english[2]="We have been waiting for the bus for one half-hour.";
english[3]="This meal is delicious";
english[4]="What day is she going to arrive?";
english[5]="We have eleven minutes before the train leaves!";
english[6]="Living in a foreign country is a good experience.";
english[7]="Excuse me! I'm late!";
english[8]="Is this taxi free?";
english[9]="Be careful when you go down the steps.";

var french=new Array();
french[0]="Cet hôtel n'est pas loin de la Tour Eiffel.";
french[1]="A quelle 开发者_运维技巧heure arrive le train?";
french[2]="Nous attendons l'autobus depuis une demi-heure.";
french[3]="Ce repas est délicieux";
french[4]="Quel jour va-t-elle arriver?";
french[5]="Nous avons onze minutes avant le départ du train!";
french[6]="Habiter dans un pays étranger est une bonne expérience.";
french[7]="Excusez-moi! Je suis en retard!";
french[8]="Est-ce que ce taxi est libre?";
french[9]="Faites attention quand vous descendez l'escalier.";

Here are the functions I am working on:

function setUpTranslation() {
   var phrases = document.getElementsByTagName("p");

   for (i = 0; i<phrases.length; i++) {
      phrases[i].number = i;
      phrases[i].childNodes[1].innerHTML = french[i];

      phrases[i].childNodes[1].onmousedown = function() { swapFE(event); }; 
  }

}

function swapFE(e) {
       var phrase = e.srcElement; 

       var phrasenum = parseInt(phrase[1].childNodes[1].innerText);

       alert("French Number = "+phrasenum+"Phrase = "+phrase.childNodes[1]);
}


Some other pitfalls of using parseInt:

// As bryantsai and shinkou mentioned, not using the radix/base
parseInt("08");     // result is 0
parseInt("08", 10); // result is 8

// Thousands separator:
parseInt("1,000"); // result is 1
parseInt("1,000".replace(",","")); // result is 1000

// Foreign decimal separator
parseInt("2,5"); // result is 2;
parseInt("2,5".replace(",",".")); // result is still 2
parseFloat("2,5".replace(",",".")); // result is now 2.5

// Finally, using the (+) operator instead of parseInt/parseFloat
+"2";     // result is 2
+"08";    // result is 8
+"1.5";   // result is 1.5
+"1,000"; // result is NaN - cannot parse thousand separators
+"1,5";   // result is NaN - decimal point must be a .

Sometimes casting with the + operator is a better approach because an invalid number string will always give NaN, which isn't the case with parseInt, which will always return a number if the string starts with one.


This is the answer I came up with and it worked. See var phrasenum. Thanks for all your help guys!

//this function changes the French phrase to an English phrase.
    function swapFE(e) {
           var phrase = e.srcElement; 
           //phrase.innerText = english[phrase.id];
           var parent = phrase.parentNode;
           //childNodes[0] is the number of the phrase +1 
           var idnum = parent.childNodes[0];
           //parseInt takes a textstring and extracts it to make a number. Then you will subtract 1 from the number.
           var phrasenum = parseInt(idnum.innerHTML)-1;
           phrase.innerText = english[phrasenum];


  }


function swapEF(e) {
       var phrase = e.srcElement; 
       //phrase.innerText = english[phrase.id];
       var parent = phrase.parentNode;
       var idnum = parent.childNodes[0];
       var phrasenum = parseInt(idnum.innerHTML)-1;
       phrase.innerText = french[phrasenum];

}


I'm not sure what went wrong with your implementation. However, if it was the return value of parseInt doesn't seem right, maybe you should try to include the base together with the string as input. e.g.

var phrasenum = parseInt(phrase[1].childNodes[1].innerText, 10);


There are some pitfalls of using parseInt(). Maybe you should paste some of your examples that not working correctly. However, the following examples should give you some ideas (hopefully):

 // working examples
 parseInt("7"); // 7
 parseInt("8"); // 8
 parseInt("9"); // 9

 // oops ...
 parseInt("07"); // 7
 parseInt("08"); // 0
 parseInt("09"); // 0

 // should always give base
 parseInt("07", 10); // 7
 parseInt("08", 10); // 8
 parseInt("09", 10); // 9

Also it should help to check the spec: 15.1.2.2 parseInt(string , radix)


parseInt takes a text representation of a number and outputs a number as an integer.

You don't want to do that.

Change your code to be this:

function swapFE(e) { 
   var phrase = e.srcElement;  

   alert("French Number = "+this.parent.number+"Phrase = "+phrase.childNodes[1]); 
} 

In the function previous to this you set phrases[i].number = i; and phrases[i].childNodes[1].onmousedown = function() { swapFE(event); };

This means that the parent of the childNode holds the index of the phrase that is being displayed.

If this.parent.number doesn't work, try phrase.number.

Update This is how I would achieve what you want:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
    <title>test page</title>
    <script>
        var english=[];
        english[0]="This hotel isn't far from the Eiffel Tower.";
        english[1]="What time does the train arrive?";
        english[2]="We have been waiting for the bus for one half-hour.";
        english[3]="This meal is delicious";
        english[4]="What day is she going to arrive?";
        english[5]="We have eleven minutes before the train leaves!";
        english[6]="Living in a foreign country is a good experience.";
        english[7]="Excuse me! I'm late!";
        english[8]="Is this taxi free?";
        english[9]="Be careful when you go down the steps.";

        var french=[];
        french[0]="Cet hôtel n'est pas loin de la Tour Eiffel.";
        french[1]="A quelle heure arrive le train?";
        french[2]="Nous attendons l'autobus depuis une demi-heure.";
        french[3]="Ce repas est délicieux";
        french[4]="Quel jour va-t-elle arriver?";
        french[5]="Nous avons onze minutes avant le départ du train!";
        french[6]="Habiter dans un pays étranger est une bonne expérience.";
        french[7]="Excusez-moi! Je suis en retard!";
        french[8]="Est-ce que ce taxi est libre?";
        french[9]="Faites attention quand vous descendez l'escalier.";

        function pageLoad()
        {
            var main = document.getElementById("main");
            for(var i = 0; i < french.length; ++i)
            {
                var p = document.createElement("p");
                p.number = i;
                var text = document.createTextNode(french[i]);
                p.appendChild(text);
                hookEvent(p, "mousedown", swapFE);
                main.appendChild(p);
            }
        }

        function swapFE()
        {
            alert("French Number = "+this.number+" Phrase = "+this.firstChild.nodeValue);
        }

        function hookEvent(element, eventName, callback)
        {
            if(typeof(element) == "string")
                element = document.getElementById(element);
            if(element == null)
                return;
            if(element.addEventListener)
            {
                if(eventName == 'mousewheel')
                    element.addEventListener('DOMMouseScroll', callback, false);  
                element.addEventListener(eventName, callback, false);
            }
            else if(element.attachEvent)
                element.attachEvent("on" + eventName, callback);
        }
    </script>
</head>
<body onload="pageLoad()">
    <div id="main">
    </div>
</body>
<html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜