2016-03-15 79 views
0

我有这个功能更新所有图片:如何更新jQuery中每个函数的特定索引?

setInterval(function(){ 

        console.log($(".image")); 

        $(".image").each(function(index) { 

         console.log(index); 

         base_url = $(this).attr('src').split('?rand=')[0]; 
         address = base_url + '?rand=' + Math.random(); 
         $(this).attr("src", address); 

        });      
       },1000); 

这在primefaces P用于:graphicImage的:

  <ui:repeat value="#{imgController.imgList}" var="images"> 
       <p:graphicImage id="pic" class="image" url="#{images.img}?rand=0" width="360px"> 

       </p:graphicImage> 
       <p:draggable for="pic" /> 
      </ui:repeat> 

我这样做的回报的console.log:

0 image.xhtml?imgId=300335:31 
1 image.xhtml?imgId=300335:31 
2 image.xhtml?imgId=300335:31 
3 image.xhtml?imgId=300335:31 

这就是我的疑问,如果我想改为更新所有图像,有没有办法通过一个特定的索引:

each(function(index) 

例子:

each(function(3) 

如果我只是想更新第三图像?

回答

2

If I just want update the third image ?

如果你只是想更新第三图像,你可以使用.eq(3)检索像这只是第三图像:

$(".image").eq(2).attr("src", adddress); 

或者,包括你的逻辑的其余部分:

var img = $(".image").eq(2); 
var base_url = img.attr('src').split('?rand=')[0]; 
var address = base_url + '?rand=' + Math.random(); 
img.attr("src", address); 

而且,下面是一个工作片断,它会更改第三张图像的.src,然后记录结果.src属性:

var img = $(".image").eq(2); 
 
var base_url = img.attr('src').split('?rand=')[0]; 
 
var address = base_url + '?rand=' + Math.random(); 
 
img.attr("src", address); 
 

 
// log output 
 
$(".image").each(function() { 
 
    log(this.src); 
 
}); 
 

 
function log(x) { 
 
    var div = document.createElement("div"); 
 
    div.innerHTML = x; 
 
    document.body.appendChild(div); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<img class="image" src="http://dummyimage.com/100x50/0000FF/FFFFFF.jpg&text=Test?rand=1.23456789"> 
 
<img class="image" src="http://dummyimage.com/100x50/0000FF/FFFFFF.jpg&text=Test?rand=1.23456789"> 
 
<img class="image" src="http://dummyimage.com/100x50/0000FF/FFFFFF.jpg&text=Test?rand=1.23456789"> 
 
<img class="image" src="http://dummyimage.com/100x50/0000FF/FFFFFF.jpg&text=Test?rand=1.23456789">

+0

I'm收到此错误类型错误:img.attr不是一个函数 –

+0

@EdsonCezar - 如果jQuery是正确的'$'安装,你不应该得到这个错误。你可以看到它在我添加到我的答案中的代码片段中工作。 – jfriend00

相关问题