开发者

what's the difference between these two javascript expressions?

I have a <a> element that's supposed to run code and not redire开发者_如何学Cct.

here are two examples of code which I believe should have the same effect, but it wont:

this works:

<a href="#" onclick="alert('Works'); return false;" />

this won't:

<a href="#" onclick="return function() {alert('don't Work'); return false;};" />

Shouldn't they both do the same? Isn't the expression in the second attempt evaluated, calling the anonymous function and returning false?

Thanks!


The second example defines a function and returns it. It never calls it.

onclick="return function() {alert('don\'t Work'); return false;}();" 

If you call it (and fix the quoting error), then you would get the same effect.


The second line returns a function object, doesn't run it. Instead the following runs:

<a href="#" onclick="alert('Works'); return false;" >first link</a>
<a href="#" onclick="function x() {alert('don\'t Work'); return false;}; return x();" >second link</a>

Also, you need to escape ' character in "don't work".


No. This is not valid javascript, as the ' in don't prematurely ends the string. Replace don't by does not and see what happens.

And see Quentins answer on the fact you're not calling the function!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜