繁体   English   中英

如何将$(this)变量传递给另一个函数javascript

[英]how to pass $(this) variable into another function javascript

我有一个按下按钮时会调用的javascript函数。 该函数使用ajax调用来调用另一个函数。 如果/当此ajax成功完成时,我希望更改按钮的类。

$(".followUser").click(function(){
    ...
    create_friendship(that.userId, that.friendId);
    ...
}
function create_friendship(user_id, friend_id){
  $.ajax({
    type: "POST",
    ...
    success: function(data, textStatus, jqXHR){
      variableForButtonHere.html("Request sent").removeClass("btn-default").addClass('btn-info');

到目前为止,用$(this)替换variableForButtonHere无效。 我把

      var mydata = $(this).data();
      window.alert(mydata.userId); 

在两个函数中,在第一个函数中都打印,在第二个函数中,如果打印undefined

我假设必须以某种方式将$(this)传递给第二个函数。 我该怎么做呢?

您可以像这样很容易地做到这一点:

$(".followUser").click(function(){
    ...
    create_friendship($(this), that.userId, that.friendId);
    ...
}
function create_friendship(button, user_id, friend_id){
  $.ajax({
    type: "POST",
    ...
    success: function(data, textStatus, jqXHR){
      button.html("Request sent").removeClass("btn-default").addClass('btn-info');

选项1:在$.ajax调用中设置上下文

$.ajax有一个选项,将允许您设置的值, this在回调函数。 这是context

您可以像这样使用它:

$(".followUser").click(function(){
    ...
    create_friendship(that.userId, that.friendId, this);
    ...
}
function create_friendship(user_id, friend_id, setThis){
  $.ajax({
    type: "POST",
    context: setThis,    // <=== HERE ===
    ...
    success: function(data, textStatus, jqXHR){
     // === Now, `this` will refer to your button element!
     $(this).html("Request sent").removeClass("btn-default").addClass('btn-info');

选项2:jQuery.proxy()方法

使用jQuery.proxy函数在您的方法中设置this的值。

选项3:干净的JavaScript方法

更妙的是,你可以使用内置的JavaScript的方法call ,并apply于设置的值this在你的方法调用。

$(".followUser").click(function(){
    ...
    create_friendship.call(this, that.userId, that.friendId);
    ...
}
function create_friendship(user_id, friend_id, setThis){
  // Here, you can either use `context: this,` option as in first method above
  // or set your variable like so:
  var button = $(this);

  $.ajax({
    type: "POST",
    ...
    success: function(data, textStatus, jqXHR){
     // === Now, `this` will refer to your button element!
     button.html("Request sent").removeClass("btn-default").addClass('btn-info');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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