简体   繁体   中英

In JS when I 'alert()' the value of an argument passed to the function, it prints out [object Object], why?

What I'm trying to do is very simple, I want to pass string values to a JS function so that it can show them in the usual alert popup. Here's the HTML:

<div class="clickit" onclick="myfun('dog','cat')"> Hello </div>

and here's the JS:

('.clickit').click(function myfun(){
    var i=0;
    for(i=0;i<arguments.length;i++){
        alert(arguments[i]);
    }
});

Unfortunately it's not working properly, it prints out: [object Object].

Also, it's looping only once even if there are 2 arguments. I followed what is described in here: w3schools , yet it isn't working.

Any help will be appreciated.

There is no function with a public name myfun . The function in the event handler is a named function expression, so the name is only available inside that function. The code in the click attribute will crash and you can find an error message for that in the error log.

When the function is called as an event handler there is only one argument; the event object.

To call the function with parameters from the event you need a named function:

function myfun(){
  var i=0;
  for(i=0;i<arguments.length;i++){
    alert(arguments[i]);
  }
}

Then you can call it from the click attribute:

<div class="clickit" onclick="myfun('dog','cat')"> Hello </div>

or you can bind an event handler from code that calls the function:

$('.clickit').click(function(){
  myfun('dog','cat');
});

Demo:

 function myfun(){ var i=0; for(i=0;i<arguments.length;i++){ alert(arguments[i]); } } $('.clickit').click(function(){ myfun('dog','cat'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div onclick="myfun('dog','cat')"> Hello </div> <div class="clickit"> Hello </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM