マイページに表示/非表示スパンタグを入力しています。クリックするとその下の段落が表示され、もう一度クリックすると再び非表示になります。複数のクエリセレクタを使用して複数のクラスをループする
私は以前の要素すなわち上で複数のIDを設定することで、前にこれを行っている:
function pageLoad() {
display();
noDisplay();
}
function display() {
var here = document.getElementById('one');
var more = document.getElementById('show')
function visible() {
more.style.display = 'block';
here.style.display = 'none';
}
here.addEventListener('click', visible);
}
function noDisplay() {
var hide = document.getElementById('hide');
var less = document.getElementById('show');
var more = document.getElementById('one');
function inVisible() {
less.style.display = 'none';
more.style.display = 'block';
}
show.addEventListener('click', inVisible);
}
window.onload = pageLoad();
<p>Some Text</p>
<span id="one"> Show more... </span>
<p id="show" style="display: none;">Some more text... <br /><span id="hide">Less text</span></p>
をしかし、これはコードの多数の過度のラインにつながります。だから私はqueryselector
とそれをやってみましたが、私はこのファンクションで第2のqueryselector
を入力する場所を把握することはできません。ここに私の現在のコードは、それが動作しませんので、私は、どこ入力に2つ目のqueryselector
を理解していないので、それはエラーを返し、スニペットにあります:
function startUp() {
showText();
}
function showText() {
var clicker = document.getElementsByClassName('display');
var show = document.getElementsByClassName('showandhide');
for (let i = 0; i < clicker.length; i++) {
clicker[i].addEventListener('click', function() {
if (clicker[i].querySelector('show').style.display == 'none') {
show.style.display = 'inline-block';
} else
show.style.display = 'none';
});
};
}
window.onload = startUp;
<p>Some Text</p><span class="display"> ...Continue reading... </span>
<p class="showandhide">Some More Text...</p>
<p>Some Text</p><span class="display"> ...Continue reading... </span>
<p class="showandhide">Some More Text...</p>
<p>Some Text</p><span class="display"> ...Continue reading... </span>
<p class="showandhide">Some More Text...</p>
私は別の入力する必要がありますかfor
ループ、2番目のqueryselector
どこか、または私はちょうどeventListener
の余分なテキストのクラスを表すためにclassName
を変更する必要がありますか? 複数のIDと過剰なコードの以前の方法ではなく、これをやってみるのはこれが初めてです。 for
ループとqueryselectors
を入れ子にしてGoogleで検索しても効果がありません。
詳細を教えてください。 HTMLやJSにIDが表示されていません。また、そこには... – Ricky
ああ、私は、あなたの現在のHTMLの一部を含む最初のスニペットを想定していました。気にしないで。 – Xufox
あなたが表示したい段落に対応するクリック可能スパンの属性data-targetを使用します。そのスパンにクリックイベントをバインドし、データターゲット属性をチェックします。対応する要素のスタイルを設定します。 – Puzzle84