![](/img/trans.png)
[英]How to pass a variable into another function to be called - 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');
$.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');
使用jQuery.proxy
函数在您的方法中设置this
的值。
更妙的是,你可以使用内置的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.