JS Bin にデモがあります。
私がやりたいことは非常に単純です。1 つの li をクリックしてアクティブのクラスを与え、子 div をフェードインできるようにしたいと考えています。できれば同時に。
また、タイトルにもあるように、ユーザーがページを閲覧するたびにアクティブなliをランダムに変更したいのですが、可能ですか?
B
JS Bin にデモがあります。
私がやりたいことは非常に単純です。1 つの li をクリックしてアクティブのクラスを与え、子 div をフェードインできるようにしたいと考えています。できれば同時に。
また、タイトルにもあるように、ユーザーがページを閲覧するたびにアクティブなliをランダムに変更したいのですが、可能ですか?
B
これを見てください。それはあなたが望むことをするはずです。
$(document).ready(function() {
var $entries = $('#entries a');
var randomNumber = Math.floor(Math.random()*$entries.length)
$entries.click(function(e) {
e.preventDefault();
var $this = $(this);
var $li = $this.parent();
var activeEntry = $this.parents('#entries').find('li.active');
activeEntry.find('div').fadeOut(300);
activeEntry.removeClass('active');
$li.find('div').fadeIn(300);
$li.addClass('active');
});
$entries.eq(randomNumber).click();
});
これは非常に単純な例ですが、目的の結果が得られるはずです:-
$('#entries li').click(function() {
// remove active class and fade div out from all list elements
$('#entries li').removeClass('active');
$('#entries div').fadeOut();
// add active class to the clicked element and fade the div in
$(this).addClass('active');
$('div', this).fadeIn();
});
// generate a random number ranging between 0 and the number of available li's
var random = Math.floor(Math.random() * $('#entries li').length);
// trigger the click event on the random element
$('#entries li').eq(random).trigger('click');
ここにフィドルがあります