views:

38

answers:

1

hello What is the difference betwen setting the onclick function in this way: obj.onclick=new Function('functionname') and

obj.onclick=function(){ functionname();};

How can i set the onclick event removing all previrius attached? (using jquery or simply javascript) i try something like this:

$(obj).unbind('click');

$(obj).click(function() { functionname(); });

but the unbind seems to remove even the next attached events. thanks EDIT:

I set the click event using jquery:

function ON(){ 
 $('#makecorr').unbind('click');//i unbind for some reason..    
 $('#makecorr').click(function() { OFF(); }); 
} 
function OFF(){
 $('#makecorr').unbind('click');//i want to remove prev attached fun 
 //and replace it with new event 
 $('#makecorr').click(function() { ON(); }); 
} 

this doesnt work for me, when i click the object 'makecorr' it goes in loop , if i put an alert, it comes up infinitely but when i use: '

function ON(){
$('#makecorr').get(0).onclick=new Function('OFF()');
} 
function OFF()
{
 $('#makecorr').get(0).onclick=new Function('ON()');
} 

it works. strange where am i wrong?

+1  A: 

This pair of lines:

$(obj).unbind('click');
$(obj).click(function() { functionname(); });

...if executed in the order above should result in just the handler you've defined there being attached. If you're seeing other behavior, it must be something else in the script.

Regarding

What is the difference betwen setting the onclick function in this way:
obj.onclick=new Function('functionname') and
obj.onclick=function(){ functionname();};

If you're dynamically adding handlers to an element and you're already using jQuery for other reasons, you don't want to use the onclick property at all; stick to the jQuery API, to avoid really confusing yourself. :-)

Even if you're not using jQuery, you almost never want to use new Function(...). There are only very special situations where you'd need that. Mostly stick to function() { functionname(); } (or just use functionname directly).

T.J. Crowder
@user354881: Recommend updating your question with that info (formatted), it's pretty close to unreadable in a comment. I'll take a look when I get back.
T.J. Crowder