0

我的页面上有这段代码,可以<iframe>用两个按钮更改我的内容

  • 以前的
  • 下一个

它仅在我将按钮的值设置为上一个和下一个时才有效,并且我想添加功能名称以与按钮执行相同的操作,因此将按钮的名称更改为之前和之后。

--- 我想要得到的基本上是两个功能,一个与前一个相同,一个用于下一个 ---

这是代码

<input type="button" value="Previous" />
<input type="button" value="Next" />
<br />
<iframe id="frame" src="1.html">
</iframe>

<script>
    var locations = ["1.html", "2.html", "3.html","4.html"];
    var currentIndex = 0;
    var len = locations.length;

    $(document).ready(function(){
        $(':button').click(function() {
             currentIndex = this.value == "Next" ? 
             currentIndex < len - 1 ? ++currentIndex : 0 : 
             currentIndex > 0 ? --currentIndex : len - 1;
             $('#frame').attr('src', locations[currentIndex]);
        });
    });
</script>
4

2 回答 2

1

如果我理解得很好,你想要类似的东西

var locations = ["1.html", "2.html", "3.html","4.html"],
    len = locations.length;
var currentIndex = (function(){
    var index = 0;
    return function(idx) {
        if(idx === void(0)) return index;
        index = idx;
        $('#frame').attr('src', locations[index]);
    }
})();
/* To read currentIndex use `currentIndex()`
   To set currentIndex use `currentIndex(value)` */
function prev() {
    currentIndex(currentIndex() < len - 1 ? currentIndex()+1 : 0);
}
function next() {
    currentIndex(currentIndex() > 0 ? currentIndex()-1 : len - 1);
}
$(document).ready(function(){
    $('#prev')
        .val('Previous')
        .click(prev);
    $('#next')
        .val('Next')
        .click(next);
});

<input type="button" id="prev" />&nbsp;<input type="button" id="next" />
<br />
<iframe id="frame" src="1.html">
</iframe>
于 2013-10-20T01:02:47.740 回答
0

Oriol 的回答为您提供了两个功能。我会这样做:

var 位置 = ["1.html", "2.html", "3.html","4.html"],

<html>
  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(document).ready(function(){
        var locations = ["1.html", "2.html", "3.html","4.html"];
      var currentIndex = 0;
      var len = locations.length;
      function  prev() {
        if(currentIndex == 0){ 
        currentIndex = len-1;
        }else{
        currentIndex--;
        }
        $('#frame').attr('src', locations[currentIndex]);

        }
     function next() {
        if(currentIndex == len -1){ 
        currentIndex = 0;
        }else{
        currentIndex++;
        }
        $('#frame').attr('src', locations[currentIndex]);
        }
      $('#prev').click(prev);

        $('#next').click(next);
      });
    </script>
  </head>
  <body>
    <input type = "button" id = "prev" value = "Before" />&nbsp;<input type = "button" value = "After" id = "next" />
    <br />
    <iframe id="frame" src="1.html"></iframe>
  </body>
</html>
于 2013-10-20T00:46:21.660 回答