0

I have some Javascript that finds all of the hyperlinks in a page that contain 'google' for example and changes the beginning of the url to another url.

I am trying to add a class to this affected link, however I am getting a lot of 'undefined' errors in the JS console. I have tried alert($(this).innerHTML)) which showed the contents of the hyperlink - clases and whatnot. But for some reason I cannot append a class. I have also tried using this.className += " socks". That also causes an undefined error. I think I am missing something simple!

Also is there a way of using a regex in the search, I am newish to Javascript.

Here is my code:

$("a[href*='google']").each(function(){ 
      this.href = this.href.replace('http://www.google.co.uk','http://www.ask.com');
      this.href = this.href.replace('http://www.google.com','http://www.ask.com');
      $(this).addClass("socks");
  });

Thanks very much for any help!

4

3 に答える 3

2

try

$("a[href*='google']").each(function(){ 

    var href = $(this).attr('href');
    href.replace('http://www.google.co.uk','http://www.ask.com');
    href.replace('http://www.google.com','http://www.ask.com');
    $(this).attr('href', href);
    $(this).addClass("socks");
});

instead of using this.href. I guess your code doesn't reach the addClass part...

Also, use firebug (in case of firefox) or chrome developer tools (in case of chrome) for debugging. You can simply set a breakpoint, add watches, etc...

(In that case, make sure you use a so-called non-minified version of jQuery for easier debugging)

于 2012-07-28T20:43:25.593 に答える
2

There is no error with this code that i can see:

http://jsfiddle.net/p7Sgj/

See this.

于 2012-07-28T20:44:49.633 に答える
2

If your HTML code is

<a href="http://www.google.co.uk">Hello</a>
<a href="http://www.google.com">World</a>

And your CSS is

.socks {
    color:#f00;
}

Then your code should be working fine.

http://jsfiddle.net/k93TZ/2/ Working here.

It might be your html or css code.

于 2012-07-28T20:46:14.157 に答える