开发者

Onclick in <a> cause reloading of the page insted of executing JS code

开发者 https://www.devze.com 2023-03-13 04:17 出处:网络
My URL: http://www.example.com/?product=3&url=XYZ My code: <a hr开发者_Python百科ef=\"#\" onclick=\"foo();return false;\">link</a>

My URL: http://www.example.com/?product=3&url=XYZ

My code:

<a hr开发者_Python百科ef="#" onclick="foo();return false;">link</a>

After click, page is reloading, instead of executing foo() function.

JS is enabled. Body of foo():

function foo() { alert("sss"); }

Probably, this problem is caused by URL of my site. XYZ parameter is a url of a website but with something like "%C5%82%C3%B3" instead of special characters (something like after using htmlspecialchars()).

What is interesting, after click the page is reloaded with the "normal" URL, something like: http://www.example.com/?product=3&url=http://www.example.com (WITH special characters like " / ").

What can I do to resolve this problem?

EDIT Above code works fine. Thank you for your time.


Yeah, there's definitely something else going on here. Here's a minimal example that works just fine:

<html>
<body>
<a href="#" onclick="foo();return false">link</a>
<script type="text/javascript">
function foo() { alert("hi"); }
</script>
</body>
</html>

Assigning onclick inline is not a good practice, and you should be doing something like

<a id="someId" /* ... */ >
// ...
<script type="text/javascript">
function foo() { alert("hi"); return false; }
document.getElementById("someId").onclick = foo;
</script>

but in any case, the most likely culprit is that your script has a syntax error somewhere and is not loading at all. You can verify this by setting onclick="return false". If that doesn't work, it's likely you have some other event handler that's being triggered. But because the above -- all we know of your code -- works, it's unlikely anyone here can diagnose what the problem is without more information.


Edit

Nevermind this, I fully assumed your code wasn't working and the below did. But I guess the code you posted was already correct.


On a seperate note, you should avoid using attributes like onClick, create event handlers instead (I suggest looking at jQuery).


i tried the same code in my systm.the code is workin and the alert box is visible.

My code:

<a href="#" onclick="foo();return false;">link/a>

and javascript is

<script type="text/javascript">

function foo()
    {
    alert("sss"); 
 }

</script>

i am using vs2008

0

精彩评论

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