最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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?

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?

Share edited Dec 19, 2011 at 8:48 Richard Dalton 35.8k6 gold badges74 silver badges92 bronze badges asked Dec 19, 2011 at 7:52 MichaelMichael 251 silver badge4 bronze badges 1
  • Could you try to clarify what your construct this.indexOf(in array())is supposed to do? – Martin Jespersen Commented Dec 19, 2011 at 8:00
Add a ment  | 

3 Answers 3

Reset to default 3

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");

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");
        }
    );
});

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()

发布评论

评论列表(0)

  1. 暂无评论