0

I'm trying to pass a variable to a function but it isn't working.

Clicking on the DIV #getNum calls a function

<div id="getNum">GET NUM</div> 

... calling function makeID() and passing the number 17

    $(document).ready(function(){
    $("#getNum").click(function(){
        makeid(17);
        });
   });

very simple example below to show what's wanted.

function makeid(num){ // It doesn't work as the parameter isn't passed 
   var chooseLetters = "abcdefghijklmnopqrstuvwxyz";
   var loopNum=num;
  for( var i=0; i < loopNum; i++ )  // loopNum does not work!
        text += chooseLetters.charAt(Math.floor(Math.random() * chooseLetters.length));
      return text;

} // END function makeid();

/* working example */

function makeid(num){ // why can I not pass the parameter to the for loop?
//console.log(num); // console.log reads num!
var num = num; // variable num is not read!
    var loopNum = num; // works if hard coded


        var chooseLetters = "abcdefghijklmnopqrstuvwxyz";

        for( var i=0; i < loopNum; i++ )
            text += chooseLetters.charAt(Math.floor(Math.random() * chooseLetters.length));

        //console.log(text);
        return text;

    } // END function makeid();
4

2 回答 2

1

问题是你的文本变量。您必须在与它连接之前定义它。基本上,您正在尝试将字符串连接到不存在的变量。这将引发错误,您的脚本将无法运行。

text+='some text';text=text+'some text';您注意到,当您的代码中未定义文本变量时,这会出现问题。

function makeid(num){ // It doesn't work as the parameter isn't passed 
text='';
   var chooseLetters = "abcdefghijklmnopqrstuvwxyz";
   var loopNum=num;
  for( var i=0; i < loopNum; i++ )  // loopNum does not work!
        text += chooseLetters.charAt(Math.floor(Math.random() * chooseLetters.length));
      return text;

} // END function makeid();

工作小提琴

http://jsfiddle.net/kasperfish/zRGCR/1/

于 2013-09-28T20:57:25.107 回答
0

我相信一旦你说

var num = num; 

“var num”将是一个隐藏原始参数的新变量。试着把这条线去掉。

于 2013-09-28T20:54:48.293 回答