显示阵列的前4个然后接下来的4个

时间:2016-06-25 20:46:17

标签: javascript jquery arrays

我试图找出一种方法来动态显示数组中的前四个元素,就像过滤它一样。共有8项。有没有办法过滤第​​一个4.然后当他们点击下一个,它会显示接下来的四个?

$("#test").click(function(){
    fruits.splice(0, fruits.length, "Lemon", "Kiwi");
        document.getElementById("demo").innerHTML = fruits;
    });
    $("#next").click(function(){
    fruits.next++;
});

function next(number)
{
    var index = fruits.indexOf(number);
    index++;
    if(index >= fruits.length)
        index = 0;
    return fruits[index];
}

var fruits = ["Banana", "Orange", "peaches", "bananas","papaya","watermelon","strawberry","cheese"];

var col1 = ["Banana", "Orange","pies","pretzels"];
var col2 = ["Banana", "Orange"];
document.getElementById("demo").innerHTML = fruits;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p>Click the button to add and remove elements.</p>
<button id="next" onclick="next();">next</button>
<p id="demo"></p>

2 个答案:

答案 0 :(得分:1)

您可以使用slice()从数组中选择元素。

&#13;
&#13;
var fruits = ["Banana", "Orange", "peaches", "bananas","papaya","watermelon","strawberry","cheese"];

$("p").text(fruits.slice(0, 4));
$("button").click(function(){
    $("p").text(fruits.slice(4, 8));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<button>Next</button>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果你想让它在项目上旋转,在完成之后然后返回到开始这个片段就是答案。否则你可以删除显示的数组部分,以阻止它再次显示。

public class ApiObjectAdapter extends RecyclerView.Adapter<ApiObjectAdapter.MyViewHolder> {

public void setOnItemClickListener(OnItemClickListener listener) {
    this.listener = listener;
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.product_name)
    public TextView name;
    @BindView(R.id.product_rating)
    public TextView rating;
    @BindView(R.id.product_price)
    public TextView price;


    public MyViewHolder(final View view) {
        super(view);
        this.parentView = view;

        try {
            ButterKnife.bind(this, view);
        } catch (Exception e) {
            e.printStackTrace();
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null)
                    listener.onItemClick(view, getLayoutPosition());
            }
        });
    }
}
var fruits = ["Banana", "Orange", "peaches", "bananas", "papaya", "watermelon", "strawberry", "cheese", "melon"];
var items = $('#items');
var amount = 4;

function showNext() {
  var itemsToShow = fruits.slice(0, amount);
  items.text(itemsToShow);
  fruits = [...fruits.slice(amount), ...itemsToShow];
  // If wanna stop at the end just set fruit = fruits.slice(amount)
}

showNext();
$("#next").click(showNext);