jquery: bind onclick
Solution 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"]; ?>);
});
});
Solution 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;
Karem
Updated on June 04, 2022Comments
-
Karem almost 2 years
$(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); } }); }