jQuery:绑定onclick [英] jquery: bind onclick

查看:131
本文介绍了jQuery:绑定onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    $(document).ready(function() {    
    $('a#fav').bind('click', addFav(<?php echo $showUP["uID"]; ?>));
});

早于

    $(document).ready(function() {    
    $('a#fav').bind('click', addFav);
});

我添加了(<?php echo $showUP["uID"]; ?>),因为我希望在addFav ajax调用中使用用户个人资料的ID.

I added (<?php echo $showUP["uID"]; ?>) because i want the user profile´s id to work with in the addFav ajax call.

所以我在页面底部有这个,即使我没有点击a#fav,它也会运行吗?但是当我没有(id)时它不会自动运行

So i have this at the bottom of my page and now even if i havnt clicked on the a#fav it runs it? But it doesnt run itself when i dont have the (id)

在以下情况下使用addFav:

Heres addFav in case:

function addFav(id){
    $.ajax({
      url: "misc/favAdd.php",
      data: { id: id},
      success: function(){
           $('a#fav')
                 .addClass('active')
                 .attr('title','[-] Remove as favorite')
                 .unbind('click')
                 .bind('click', removeFav(id))
           ;
                jGrowlTheme('wallPop', 'mono', '[+] Favorit', 'Du har nu lagt till denna profil som favorit', 'images/addFavorit_hover2.png', 1000);
      }
    });
}

function removeFav(id){
    $.ajax({
      url: "misc/favRemove.php",
      data: { id: id },
      success: function(){
            $('a#fav')
                 .removeClass('active')
                 .attr('title','[+] Add as favorite')
                 .unbind('click')
                 .bind('click', addFav(id))
            ;
                            jGrowlTheme('wallPop', 'mono', '[-] Favorit', 'Du har nu tagit bort denna profil som favorit', 'images/addFavorit_hover2.png', 1000);
      }
    });
}

推荐答案

bind函数的第二个参数是函数本身.当您将函数作为参数传递时,您必须仅提供函数名称,而不能提供左/右括号或参数.

The second parameter to the bind function is a function itself. When you pass a function as a parameter, you must only supply the function name, not the opening/closing parenthesis or arguments.

在您的情况下,如果您想将参数传递给addFav函数,则可以通过将匿名函数传递给bind来实现,然后在该函数的主体内,以您自己的方式调用addFav通常会用您的参数.像这样:

In your case, if you'd like to pass parameters to the addFav function, you may do so by passing an anonymous function to bind, and within the body of that function, call addFav as you normally would with your parameters. Like this:

$(document).ready(function() {    
    $('a#fav').bind('click', function() {
        addFav(<?php echo $showUP["uID"]; ?>);
    });
});

这篇关于jQuery:绑定onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆