user2986042 user2986042 - 2 months ago 9
Javascript Question

How to get a anchor link text inside a javascript and calling with arguments

I wrote a function like to get a user from server and i got it . Now i create a links for each users using

a href
inside
java script
. This is working fine . Now i want to execute a function when i user click the link (with the corresponding user name)

var User_id = document.querySelector(".sidebar-name");

//getting array of user

function list(user){

User_id.innerHTML = "";

for( i = 0; i < user.length; i++ ){

User_id.innerHTML+= "<a href='#' onclick = 'javascript:calluser(this);' style='text-decoration:none'>" + user[i] + "</a>" + "<br />";

}
}



function calluser(this){

alert(user);
// i need to print the corresponding username or anchor text .
// how can i solve this ?

}


I tried with
id
inside
a href
. But this is not unique so it won't work . How can i solve this ?

Answer

"function calluser(this) " Is a Syntax error.

Rename "this" with something else like "a":

var User_id = document.querySelector(".sidebar-name");

function list(user){
    User_id.innerHTML = "";
    for(var i=0; i<user.length; i++){
        User_id.innerHTML+= "<a href='jacascript:void();' onclick='javascript:calluser(this);' style='text-decoration:none'>" + user[i] + "</a>" + "<br />";
    }
}

function calluser(a){
    alert(a.text);
}
Comments