簡體   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