简体   繁体   中英

Javascript: Can't pass variables as parameters with onClick

I have this code (jquery):

function somefunction() {

        $.ajax({
        type : 'POST',
        url : 'post.php',
        dataType : 'json',

        success : function(data){

            var mess = "";  
            var count = 0;

            while (count < (data.length - 1))
            {

                 mess = mess + "<a href=# onclick=deletePerson("JohnDoe");return false;><img src=x.gif></a>" + data[count].name + "<br />";
                 count++;
            }


            $('#mydiv').html(mess).fadeIn('fast');


        },
    });


}
function deletePerson(arg) {...}

When I run this, everything works fine. However, when I want to pass a variable (instead of "JohnDoe") with the onclick, it stops working:

var myvar = "JohnDoe";
mess = mess + "<a href=# onclick=delete(myvar);return false;><img src=x.gif></a>" + data[count].name + "<br />";

My editor tells me: "Unresolved variable or type".

Never had a problem with passing parameters, but with this onClick-thing it just doesn't work...

Anyone knows what I'm doing wrong?

Thank's a lot!

EDIT: Joseph's post fixed the JohnDoe problem (thanks!), however, when I put:

var myvar = data[count].name;

it stops working... any thoughts?

You need to concatenate the variable in

myvar = "JohnDoe";
mess = mess + "<a href=# onclick=delete('"+myvar+"');return false;><img src=x.gif></a>" + data[count].name + "<br />";

delete is a reserved keyword in javascript, you should rename your function.

...
mess = mess + "<a href=# onclick=deletePerson('"+myvar+"');return false;><img src=x.gif></a>" + data[count].name + "<br />";
...
function deletePerson(name) {...}

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