开发者

Why is this 'href' value not working in Opera?

开发者 https://www.devze.com 2023-02-11 20:20 出处:网络
I have the following: <a href=\"javascript:jQuery(\'body\').css(\'backgroundColor\',\'red\');\">Test</a>

I have the following:

<a href="javascript:jQuery('body').css('backgroundColor','red');">Test</a>

When run in Chrome, it functions as expected and turns the page red. However, in Opera I get:

[object Object]

Closer inspection reveals that Opera thinks that javascript:Query('body')... is some kind of URL. What am I doing wrong? Doesn't Opera recognize javascript: links in the开发者_如何学编程 href attribute?

jsFiddle: http://jsfiddle.net/9CZZL/


Edit: seems to be a Firefox problem too...


The issue is that the return value of jQuery('body').css('backgroundColor','red') is an object, which some browsers interpret as the new content for the web page. To fix this, you can use the JavaScript void operator to turn it into undefined, which FF and Opera (and potentially others) will handle as you intended. You will notice that this issue is also described on that page, since it's the premier use-case of the void operator (other than code golf where void 0 is less characters than undefined).

<a href="javascript:void(jQuery('body').css('backgroundColor','red'));">Test</a>

This should give the intended result: http://jsfiddle.net/9CZZL/13/

It should be noted that handling clicks this way is considered bad practice. Instead, using event handlers in JavaScript is recommended. This helps separate the different layers of your web app, which in turn will make debugging in the future easier.


I just did a google search and no, apparently Opera does not recognise "javascript:" href values. You would have to implement an onClick or similar solution.


Does it in Firefox too.... not quite sure why. But I never liked putting JavaScript right in the URL... you could try putting it in the onclick event or pull the whole thing out and separate it:

http://jsfiddle.net/mnbayazit/6d5An/


These all work as href values for me in Opera 10.1:

javascript:void(0)
javascript:alert("Hello")
javascript:window.location.href = 'http://www.google.com'

Your snippet does not though.

A viable work around is:

<a href="#" onclick="$('body').css('background-color','red')">Test</a>

Or even:

<a href="javascript:void(0)" onclick="$('body').css('background-color','red')">Test</a>

...since that seems to work.

0

精彩评论

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