javascript void(0) problem in IE

2019-05-17 09:07发布

问题:

HI,

I am developing a web page using asp.net.

I am using some links in my web page. For that I have used some code like this.

<a href="javascript:void(0);" onclick="javascript:ChangeLoc('TEST','');">Test</a>

and in the ChangeLoc() method I have written __doPostBack event.

This works fine in IE7 installed in my machine. But in IE6 in another machine it does not invoke the __doPostBack event.

Edit

When I change the void(0) in href it works fine.

I would like to know whether it is a bug with IE or a JavaScript problem.

function ChangeLoc( param, arg )
{
     __doPostBack ( param, arg )
}

回答1:

href and onclick both get fired when you click an element, you are overwriting the onclick event with void()

change to

<a href="#" onclick="ChangeLoc();return false">test</a>

or with jQuery.

$(function(){
  $("#linkId").click(function(event){
      ChangeLoc();
      event.preventDefault();
  });
}); 


回答2:

Do you get an error? If so, what error do you get in IE6? Can you post the code for ChangeLoc()? Also, try changing your markup to the following and see if you get the same result:

<a href="#" onclick="ChangeLoc(); return false;">Test</a>

Edit: removed 'javascript:' from the onclick



回答3:

You can also use unobtrusive javascript syntax:

<a href="index.html" id="chngLink">test</a>

<script type="text/javascript">
document.getElementById("chngLink").onclick = function(e) {
    if (e && e.preventDefault) {
        e.preventDefault();
    }
    ChangeLoc('TEST','');
    return false;
};
</script>


回答4:

it is not good to use <a>-element for javascript functions call. Use styled <span onclick="my_function()" class="looks_like_hyperlink">...</span>