jQuery следующий div по клику с циклом - PullRequest
0 голосов
/ 02 апреля 2020

Эй, мне нужна своего рода текстовая галерея. Если вы нажмете на первый текст, второй текст должен заменить первый текст, если вы нажмете на второй текст, третий текст должен заменить второй текст и так далее. И если вы нажмете на последний текст, первый текст должен заменить последний текст.

Я начал с этого:

$( ".text" ).click(function() {
$( this ).css("display", "none");
$( next ).css("display", "block");
});
.text {
display: none;
}

.text:hover {
color: blue;
cursor: pointer;
}

.text:nth-child(1) {
display: block;
}
<div class="text">The cat (Felis catus) is a domestic species of small carnivorous mammal. It is the only domesticated species in the family Felidae and is often referred to as the domestic cat to distinguish it from the wild members of the family. A cat can either be a house cat, a farm cat or a feral cat; the latter ranges freely and avoids human contact. Domestic cats are valued by humans for companionship and their ability to hunt pests such as rodents. About 60 cat breeds are recognized by various cat registries.</div>

<div class="text">The cat is similar in anatomy to the other felid species: it has a strong flexible body, quick reflexes, sharp teeth and retractable claws adapted to killing small prey. Its night vision and sense of smell are well developed. Cat communication includes vocalizations like meowing, purring, trilling, hissing, growling and grunting as well as cat-specific body language.</div>

<div class="text">Female domestic cats can have kittens from spring to late autumn, with litter sizes ranging from two to five kittens.</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Я не знаю, как написать эту функцию. Кто-нибудь может мне помочь? Было бы так здорово.

Ответы [ 3 ]

1 голос
/ 02 апреля 2020
  • Используйте оператор по модулю %, чтобы вернуться к 0 для индекса curr
  • Используйте jQuery * .eq(), чтобы получить спецификацию c index element.

const $text = $('.text'); // Cache all 
const tot = $text.length; // How many
let curr = 0; // Set index to 0 (First text)

$text.on('click', () => {

  const $next = $text.eq(++curr % tot); // Increment and loopback
  $text.not($next).hide();
  $next.show();

});
.text {
  display: none;
}

.text:hover {
  color: blue;
  cursor: pointer;
}

.text:nth-child(1) {
  display: block;
}
<div class="text">1 The cat (Felis catus) is a domestic species of small carnivorous mammal. It is the only domesticated species in the family Felidae and is often referred to as the domestic cat to distinguish it from the wild members of the family. A cat can either be
  a house cat, a farm cat or a feral cat; the latter ranges freely and avoids human contact. Domestic cats are valued by humans for companionship and their ability to hunt pests such as rodents. About 60 cat breeds are recognized by various cat registries.</div>
<div class="text">2 The cat is similar in anatomy to the other felid species: it has a strong flexible body, quick reflexes, sharp teeth and retractable claws adapted to killing small prey. Its night vision and sense of smell are well developed. Cat communication includes
  vocalizations like meowing, purring, trilling, hissing, growling and grunting as well as cat-specific body language.</div>
<div class="text">3 Female domestic cats can have kittens from spring to late autumn, with litter sizes ranging from two to five kittens.</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
1 голос
/ 02 апреля 2020

используя next () и проверяя длину

var elems = $(".text")
elems.on("click", function() {
  var elem = $(this).css("display", "none");
  var next = elem.next('.text')
  if (!next.length) next = elems.eq(0)
  $(next).css("display", "block");
});
.text {
  display: none;
}

.text:hover {
  color: blue;
  cursor: pointer;
}

.text:nth-child(1) {
  display: block;
}
<div class="text">The cat (Felis catus) is a domestic species of small carnivorous mammal. It is the only domesticated species in the family Felidae and is often referred to as the domestic cat to distinguish it from the wild members of the family. A cat can either be
  a house cat, a farm cat or a feral cat; the latter ranges freely and avoids human contact. Domestic cats are valued by humans for companionship and their ability to hunt pests such as rodents. About 60 cat breeds are recognized by various cat registries.</div>

<div class="text">The cat is similar in anatomy to the other felid species: it has a strong flexible body, quick reflexes, sharp teeth and retractable claws adapted to killing small prey. Its night vision and sense of smell are well developed. Cat communication includes
  vocalizations like meowing, purring, trilling, hissing, growling and grunting as well as cat-specific body language.</div>

<div class="text">Female domestic cats can have kittens from spring to late autumn, with litter sizes ranging from two to five kittens.</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

или с удалением и добавлением массива

var elems = $(".text")
var arrElems = elems.get()
elems.on("click", function() {
  var elem = $(this).css("display", "none");
  arrElems.push(arrElems.shift())
  $(arrElems[0]).css("display", "block");
});
.text {
  display: none;
}

.text:hover {
  color: blue;
  cursor: pointer;
}

.text:nth-child(1) {
  display: block;
}
<div class="text">The cat (Felis catus) is a domestic species of small carnivorous mammal. It is the only domesticated species in the family Felidae and is often referred to as the domestic cat to distinguish it from the wild members of the family. A cat can either be
  a house cat, a farm cat or a feral cat; the latter ranges freely and avoids human contact. Domestic cats are valued by humans for companionship and their ability to hunt pests such as rodents. About 60 cat breeds are recognized by various cat registries.</div>

<div class="text">The cat is similar in anatomy to the other felid species: it has a strong flexible body, quick reflexes, sharp teeth and retractable claws adapted to killing small prey. Its night vision and sense of smell are well developed. Cat communication includes
  vocalizations like meowing, purring, trilling, hissing, growling and grunting as well as cat-specific body language.</div>

<div class="text">Female domestic cats can have kittens from spring to late autumn, with litter sizes ranging from two to five kittens.</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
1 голос
/ 02 апреля 2020

Попробуйте это:

$( ".text" ).click(function() {
    $( this ).css("display", "none");
    var next = $(this).next();
    if (next.text() == ''){
        $(".text").first().css("display", "block");
    }
    else{
        next.css("display", "block");
    }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...