Changing onclick event using jQuery

I have a javascript snippet that displays a widget on my page. There are links that are output using a script that look like this:

<a href="#" onclick="somefunction()">Link</a>

These links force JS to run. It's great. The problem is the href="#"lack of a "return false;"at the end of the attribute onclick.

When I click one of these links, the browser goes to the top of the document. If the widget is located close to the bottom of the document, this is not good.

Unfortunately, I do not control the output of the script.

Using jQuery, I can link to these links using $("#wxheader ul li a"). I tried the following code, but it does not work:

$(document).ready(function(){
    $("#wxheader ul li a").each(function(){
        var onclick = $(this).attr("onclick") + "; return false;";
        $(this).attr("onclick", onclick );
    });
});

jQuery, onclick, "return false;", , script .

?

+5
6

. preventDefault , . , .

$("#wxheader ul li a").click(function(e){
  e.preventDefault();
  return false;
});
+4

jquery, :

$("#wxheader ul li a").each(function(){
    $(this).click(function(e) {
        e.preventDefault();
    });
});

click.

,

+2

href="javascript:"?

+2

:

<a href="javascript:void(0)" onclick="somefunction()">Link</a>
+2

:

$( '#wxheader ul li a' ).each( function( i, element )
{
  // Capture the existing callback function
  var originalCallback = element.onclick;

  // Now, remove it from the elemnet
  element.onclick = null;

  // And replace it with our own, which calls the orignal
  // with the proper context, and prevents the default
  // event action
  $(element).click( function( event )
  {
    event.preventDefault();
    originalCallback.call( window );
  });
});
+2

preventDefault jQuery.

http://api.jquery.com/event.preventDefault/

This will prevent it from starting initially or adding false to the jQuery handler. preventDefault may not work in Firefox. I'm not quite sure.

$("#wxheader ul li a").click(function(){ 
   //do stuff//
    return false;
});

This is a test page that I did with some ajax functions by reference for someone trying to override a regular click. this is the functionality that I'm talking about, if that's what you are looking for.

http://testing.kobbyappiah.com/Design_and_Evolve/ajaxTest.html

+2
source

All Articles