簡體   English   中英

在jquery中有像indexof()這樣的方法嗎? 或者怎么做?

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

看下面的代碼:

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

如果我不使用“ id”,則只需使用“ this.indexof()”。 下面的代碼是錯誤的,但我想讓您知道我的意思:

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

我怎么能在jquery中這樣做?

是的,它是.index()方法:

如果沒有參數被傳遞給所述的.index()的方法,所述返回值是表示所述第一元素的jQuery對象相對於其兄弟元素中的位置的整數。

使用它作為$(this).attr("src","images/" + $(this).index() + "_hover.gif");

我將研究jQuery .each方法 ,因為它提供了一個索引。

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

indexOf()可用於字符串對象。

如果要通過jquery在attr上使用它,則應嘗試以下操作:

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

更多信息:
JavaScript indexOf()
jQuery attr()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM