简体   繁体   中英

jQuery - Trouble adding a class to a hyperlink using 'each'

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!

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)

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

http://jsfiddle.net/p7Sgj/

See this.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM