简体   繁体   中英

How to send the Id of this anchor as a function parameter?

Edit: Sorry guys, I got the issue, Misspelled class name :(
Hey, I got a quick question for your guys here. I have some anchor tags each of them points to a url of a certain user. The link id is the username. All the links share a css class (.userset). When a user clicks the link I need to issue an Ajax request -using jQuery.ajax method- to a server resource passing in the id of the link. Here's how my code looks like:
JS

 $(".columnist_set .img").click(function() {

        alert("this.id =" + this.id);
        var x = track(this.id);
});

This doesn't seem to work for me! this.id is always undefined.
Yeah, I'm suer I'm missing something, so what am I missing dear SO Gus?

Edit (I was on the wrong track because of some probably incorrect assumptions)

Try the following:

$(".columnist_set .img").click(function() {
        var id = $(this).attr("id");
        alert("id =" + id);
        var x = track(id);
});

你可以试试

$(this).attr("id");

You can try this:

$(".userset").click(function() {
   var x = track($(this).attr("id"));
});

Reading your request i can feel some confusion.

Your request says:

I have some anchor tags each of them points to a url of a certain user.

With this sentence you mean you have many <a> in your code, with the href attribute pointing to some user-driven path.

The link id is the username. All the links share a css class (.userset).

More info, why not. Your tag now should look in my mind like <a class=".userset" id="myUserName" href="./some/url">content</a>

When a user clicks the link I need to issue an Ajax request -using jQuery.ajax method- to a server resource passing in the id of the link

Let's add the click event:

   //all the anchor tags with "userset" class
   $('a.userset').click(
      function(){
          //doing the ajax call
          $.ajax({
              type: "POST",
              url: $(this).attr("href"),      //picking the href url from the <a> tag
              data: "id=" + $(this).attr("id"),    //sanitize if it's a free-inputed-string
              success:
                function(result) {
                    alert("I AM THE MAN! Data returned: " + result);
                }
              }
          );
      }
   );

With that being said, i can't really understand what your javascript code (with references to .img class ?) is referring to.

Hope my answer helped a bit though.

The problem is that, I misspelled the class name so the returned wrapped set of my selector is undefined. Thanks for your help all though.

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