Michael
Michael

Reputation: 25

Is there something method like indexof() in jquery? Or how to do that?

Look at the code below:

$(".head img").hover(function(){
    var id = $(this).attr('id');
    $(this).attr("src","images/"+id+"_hover.gif");
},function(){
    var id = $(this).attr('id');
    $(this).attr("src","images/"+id+".gif");
})

If I do not use the "id",just use "this.indexof()" something like this. the code below is wrong, but i want you to know what i mean:

$(".head .fl_r img").hover(function(){
    $(this).attr("src","images/"+this.indexof(in array())+"_hover.gif");
},function(){
    $(this).attr("src","images/"+this.indexof(in array())+".gif");
})

How can i do that in jquery?

Upvotes: 1

Views: 8833

Answers (3)

Filip Dupanović
Filip Dupanović

Reputation: 33690

Yes, it's the .index() method:

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

Use it as $(this).attr("src","images/" + $(this).index() + "_hover.gif");

Upvotes: 3

Grrbrr404
Grrbrr404

Reputation: 1805

indexOf() is available for string objects.

If you want to use it on a attr via jquery, you should try this:

$(this).attr("src").indexOf("needle");

More info:
JavaScript indexOf()
jQuery attr()

Upvotes: 0

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59151

I'd look into the jQuery .each method, as it provides an index.

$(".head img").each(function(index, element) {
    element.hover(
        function() {
            $(this).attr("src","images/"+index+"_hover.gif");
        },
        function() {
            $(this).attr("src","images/"+index+".gif");
        }
    );
});

Upvotes: 1

Related Questions