0

我试图将图像放置在 div 中,以便可以控制 h/w,我似乎可以让它与 jquery 3.2.1 一起使用它只适用于 jquery 2.1.1,有没有更好的写法这段代码,我试图简单地单击“下一步”div并使用循环更改图像。

$(function() {
var images = [
  "http://placehold.it/300x150/f0f&text=1"
  ,"http://placehold.it/300x150/cf5&text=2"
  ,"http://placehold.it/300x150/b15&text=3"
  ,"http://placehold.it/300x150/c59&text=4"
  ,"http://placehold.it/300x150/ac2&text=5"
  ,"http://placehold.it/300x150/bb5&text=6"
];

// ======================================

var tot = images.length;
var c = 0; // current image

function loadImage(){
  $("<img/>").attr("src",images[c]).load(function() {
      $('#gallery').html( this );
  }); 
}
loadImage(); // for the page load

$('#prev').click(function(){
  id=this; c--;
  c=c==-1?tot-1:c%tot;
  loadImage(); 
});

$('#next').click(function(){
  id=this; c++;
  c=c==-1?tot-1:c%tot;
  loadImage(); 
});
});
#gallery{
    width:150px;
    height:50px;
    background:#ddd;
    margin-top:8px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pagination">
  <div id="prev" class="btn" style="position:">PREV</div>
  <div id="next" class="btn" style="position:">NEXT</div>
</div>
  
<div id="gallery">
  
  
</div>

4

2 回答 2

0

在 3.X 中删除了使用 load() 作为事件绑定。它现在仅用于获取资源,第一个参数是要检索的资源的 url。

http://api.jquery.com/load/

“注意:在 jQuery 3.0 之前,事件处理套件还有一个名为 .load() 的方法。旧版本的 jQuery 会根据传递给它的参数集确定要触发的方法。”

使用 on('load') 代替。

于 2017-05-26T17:58:21.930 回答
0

代替

$("<img/>").attr("src",images[c]).on("load", function() {
  $('#gallery').html( this );
});

为了

$("<img/>").attr("src",images[c]).load(function() {
  $('#gallery').html( this );
});
于 2017-05-26T17:58:52.483 回答