Skip to content
Advertisement

How to replace onClick event dynamically?

I have following page:

<body>

<a href="#" id=key onclick="func(0)">foo</a>

</body>
</html>
<script type="text/javascript">
function func(k){
    alert(k);
    $('#key').click(function() {func(++k)});
}   
</script>

My expectations of this code execution following:

I click on link and see 0, then click one more time and see 1, then click one more time and see 2….then 3….4…5….6

But actual result:

I click on link and see 0,
I click on link and see 0 and then 1 twice,
I click on link one more time and see 0 2 2 2 2 and 1.

Please help to understand what does happen and and how to rewrite it?

Update

Key of the question is invocation of old function with new argument on onclick action!

Advertisement

Answer

I rewrote function like this:

function func(k){
    alert(k);
    $("#key").removeAttr('onclick');
    $("#key").unbind('click')   
    $('#key').click(function() {func(++k)});
}   

and I see expected result

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement