更改onclick

时间:2011-04-30 21:40:41

标签: javascript jquery

好的,我有这个

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

还是有更好的或其他方式

3 个答案:

答案 0 :(得分: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);

然后当你想切换&gt;

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

答案 1 :(得分:2)

通常的方法(即将事件绑定到事件)是bindclick

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

答案 2 :(得分: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只是一个示例