2011-04-30 60 views
3

好了,所以我有这个改变的onclick

<img width="38" height="39" onclick="jreviews.favorite.add(this,{listing_id:2655})" class="imgFavoriteAdd" alt="Add to favorites" id="jr_favoriteImg2655" src="http://kingdomshopper.com/templates/jreviews_overrides/views/themes/default/theme_images/fav_add.png"> 

,正如你所看到的onclick是

jreviews.favorite.add(this,{listing_id:2655}) 

我需要的onclick改变

jreviews.favorite.remove(this,{listing_id:2655}) 

但是当我做

jQuery("#jr_favoriteImg2655").attr("onclick") 
onclick(event) 

能做些

jQuery("#jr_favoriteImg2655").attr("onclick", "jreviews.favorite.add(this,{listing_id:2655})") 

或是否有更好的或另一种方式

回答

4

你会很多更好,如果您从元素中删除onclick属性,然后执行以下>

// Initializing >> 
var first = function() { jreviews.favorite.add(this,{listing_id:2655}) }; 
var second = function() { jreviews.favorite.remove(this,{listing_id:2655}) }; 

jQuery("#jr_favoriteImg2655").bind("click", first); 

,然后当你想切换>

jQuery("#jr_favoriteImg2655").unbind("click", first); 
jQuery("#jr_favoriteImg2655").bind("click", second); 
+1

几乎PE rfect;我建议你将'.unbind()'和'.bind()'调用链接在一起,因为它们使用相同的包装元素。 – 2011-05-01 05:21:49

2

通常的方法来做到这一点(即结合功能的事件)或者是bindclick

jQuery("#jr_favoriteImg2655").click(function() { 
    jreviews.favorite.remove(this,{listing_id:2655}); 
}); 
2

使用内联不建议的JavaScript,但无论如何你可以在这里使用的条件,以确保你之前或不添加此收藏。事情是这样的:

<img width="38" height="39" onclick="if(!jreview.favorite.exist(this)){jreviews.favorite.add(this,{listing_id:2655})}else{jreviews.favorite.remove(this,{listing_id:2655})}" class="imgFavoriteAdd" alt="Add to favorites" id="jr_favoriteImg2655" src="http://kingdomshopper.com/templates/jreviews_overrides/views/themes/default/theme_images/fav_add.png"> 

我不熟悉你的API和exist只是一个例子