Reputation:
I want to recolor all the links within obj
array in a page if they match the number in procura
.
So, obj = [6849,6850]
And procura
is defined below:
function getLastNumberOfString(str){
var allNumbers = str.replace(/[^0-9]/g, ' ').trim().split(/\s+/);
return parseInt(allNumbers[allNumbers.length - 1], 10);
}
jQuery(function() {
jQuery('a.mod-articles-category-title').each(function () {
var $link=jQuery(this);
var href=$link.attr('href');
var procura = getLastNumberOfString(href)
jQuery.each(obj,function(_,test) {
if(test.indexOf(procura)!=-1) { // only works on strings
jQuery(this).css({'color':'#45AAA2'});
jQuery(this).delay(1000);
jQuery(this).animate({
color:"#CCCCCC"
},3000);
}
});
});
});
This is returning the error: Uncaught TypeError: Cannot use 'in' operator to search for 'color' in undefined
I think it is because this
is not correctly defined, but how to fix it?
Upvotes: 3
Views: 61
Reputation: 3368
For selecting the links, you'd want to check out the jQuery [attribute*=value] Selector. It allows you to select all links with an attribute containing a certain string. You'd be able to just write a loop to build selectors that look like this $("[href*='6849']")
obj = [6849,6850]
obj.forEach(function(code){
var selector = "[href*='" + code + "']";
$(selector).css({'color':'#45AAA2'});
... etc
})
Upvotes: 0
Reputation: 35670
Within the nested each()
method, this
refers to each element of the array. Instead, you want it to refer to each anchor in the jQuery collection returned by the outermost each()
.
Store the current anchor in a variable for use in the nested each()
method. You've already created that variable, named $link
:
$(function() {
$('a.mod-articles-category-title').each(function() {
var $link = $(this);
var href = $link.attr('href');
var procura = getLastNumberOfString(href);
$.each(obj, function(_, test) {
if (test.indexOf(procura) != -1) { // only works on strings
$link.css({
'color': '#45AAA2'
});
$linkdelay(1000);
$link.animate({
color: "#CCCCCC"
}, 3000);
}
});
});
});
Upvotes: 1