If I want to filter a set of links against an array and then style those not in the array as unavaible, how would I do that.
Here is what I have:
if (this.id == '93') {
$links.filter(function() {
}).addClass('unavailable');
But I don't know how the syntax for checking against an a开发者_Python百科rray.
The short answer...
Use jQuery's $.inArray(value, array)
function.
Also, see this Stackoverflow question, Javascript - array.contains(obj), whose answer mentions jQuery's $.inArray
function as well as array searching functions in other JavaScript libraries.
The long answer...
I presume you have an collection of hyperlinks on your page, like so:
<p><a id="google" href="http://www.google.com/">Google</a></p>
<p><a id="yahoo" href="http://www.yahoo.com/">Yahoo!</a></p>
<p><a id="ask" href="http://www.ask.com/">Ask</a></p>
<p><a id="icerocket" href="http://www.icerocket.com/">Icerocket</a></p>
And that you have an array that contains the id
s of those hyperlinks, like so:
var validLinkIds = ["google", "ask"];
The following script will filter across all <a>
elements, "disabling" those that are not in the validLinkIds
array:
$("a").filter(function() {
if ($.inArray($(this).attr('id'), validLinkIds) < 0)
$(this).removeAttr('href');
});
I created a JSFiddle entry where you can run/test out this script - http://jsfiddle.net/qMhWQ/
Happy Programming!
精彩评论