イベントが発生した時点で要素に存在するテキスト値に応じて、クリック時に特定の要素のテキストを変更する次のコードがあります。
$('#left').on('click', function (){
if ($("#textContainer:contains('something')").length) {
$('#textContainer').text('third text replacement');
$('.elsewhere').text('more here');
}
else if ($("#textContainer:contains('third text replacement')").length) {
$('#textContainer').text('now the next item');
$('.elsewhere').text('something new here');
}
else if ($("#textContainer:contains('now the next item')").length) {
$('#textContainer').text('new text here');
$('.elsewhere').text('something else here');
}
else if ($("#textContainer:contains('new text here')").length) {
$('#textContainer').text('something');
$('.elsewhere').text('text here');
}
});
$('#right').on('click', function (){
if ($("#textContainer:contains('something')").length) {
$('#textContainer').text('new text here');
$('.elsewhere').text('something else here');
}
else if ($("#textContainer:contains('new text here')").length) {
$('#textContainer').text('now the next item');
$('.elsewhere').text('something new here');
}
else if ($("#textContainer:contains('now the next item')").length) {
$('#textContainer').text('third text replacement');
$('.elsewhere').text('more here');
}
else if ($("#textContainer:contains('third text replacement')").length) {
$('#textContainer').text('something');
$('.elsewhere').text('text here');
}
});
動作するバージョンについては、上記のフィドルを参照してください。
これをさらに簡単に拡張できるようにするために、これをより管理しやすくする方法を見つけたいと思います。このケースを処理するためのより良い方法はありますか? これを関数に凝縮し、変数を使用して #textContainer の値を格納するのがより理想的です。助言がありますか?