【问题标题】:How to send the Id of this anchor as a function parameter?如何将此锚点的 ID 作为函数参数发送?
【发布时间】:2009-10-12 10:00:05
【问题描述】:

编辑:对不起,我遇到了问题,拼写错误的类名:(
嘿,我在这里有一个快速的问题要问你们。我有一些锚标签,每个标签都指向某个用户的 url。链接 id 是用户名。所有链接共享一个 css 类 (.userset)。当用户单击链接时,我需要使用 jQuery.ajax 方法向传递链接 ID 的服务器资源发出 Ajax 请求。我的代码如下所示:
JS

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

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

这似乎对我不起作用! this.id 始终未定义。
是的,我很害怕我错过了一些东西,所以我错过了什么亲爱的 SO Gus?

【问题讨论】:

    标签: javascript jquery asp.net-mvc


    【解决方案1】:

    你可以试试

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

    【讨论】:

      【解决方案2】:

      你可以试试这个:

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

      【讨论】:

        【解决方案3】:

        编辑(由于一些可能不正确的假设,我走错了方向)

        尝试以下方法:

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

        【讨论】:

        • 我不确定出了什么问题。它只是不适合我。你确定这会给我主播的 id 吗?
        【解决方案4】:

        阅读您的请求,我感到有些困惑。

        您的请求说:

        我有一些锚标签 他们每个人都指向一个 url 某个用户。

        这句话的意思是你的代码中有很多<a>href 属性指向一些用户驱动的路径。

        链接 id 是用户名。所有链接共享一个 CSS 类(.userset)。

        更多信息,为什么不呢。你的标签现在应该在我的脑海中看起来像 <a class=".userset" id="myUserName" href="./some/url">content</a>

        当用户点击 我需要发布 Ajax 的链接 请求 - 使用 jQuery.ajax 方法 - 到 传入 id 的服务器资源 链接

        让我们添加点击事件:

           //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);
                        }
                      }
                  );
              }
           );
        

        话虽如此,我真的无法理解您的 javascript 代码(引用 .img 类?)指的是什么。

        希望我的回答对你有所帮助。

        【讨论】:

          【解决方案5】:

          问题是,我拼错了类名,所以我的选择器返回的包装集是未定义的。不过感谢您的帮助。

          【讨论】:

            猜你喜欢
            • 2016-12-04
            • 2020-11-28
            • 2021-07-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多