jquery: bind onclick

雨燕双飞 提交于 2019-12-11 07:23:33

问题


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

was before

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

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

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)

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

回答1:


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.

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"]; ?>);
    });
});



回答2:


You need an anoymous function like this onload:

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

And this style in your success callbacks:

$('#fav').click(function() {
  addFav(id);
});

since #fav should be a unique ID, it's a much faster selector.


Or, pass it as the data argument to .bind(), like this:

$('a#fav').bind('click', { id: id }, addFav);

And in your function access it that way instead of as a parameter, like this:

function addFav(e){
  var id = e.data.id;


来源:https://stackoverflow.com/questions/3646162/jquery-bind-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!