2017-04-22 4 views
3

にOnclick javascript関数もう一度クリックするだけに取り組ん

function toggleDivFunction() { 
 
    var arrowElement = document.getElementById("arrowRight"); 
 
    var showElement = document.getElementById("dropdownText"); 
 
    arrowElement.onclick = function() { 
 
    if (showElement.style.display == 'none') { 
 
     showElement.style.display = 'block'; 
 
     document.getElementById("arrowRight").style = "transform: rotate(+90deg)"; 
 
    } else { 
 
     showElement.style.display = 'none'; 
 
     document.getElementById("arrowRight").style = "transform: rotate(0deg)"; 
 
    } 
 
    } 
 
}
<p class="dropdownHeader">TOP <span id="arrowRight" class="arrowRight" onclick="toggleDivFunction();"> > </span></p> 
 
<div class="dropdownText" id="dropdownText"><p>TEXT TO BE SHOWN</p></div>

問題はdropdownTextのdivだけarrowRightスパンを2回目にクリックした後に表示されることです。 私はそれを共通の問題として見てきましたが、まだ解決策を見つけることに失敗しました。どんな助けもありがとう。

+0

これを単に削除してください:arrowElement.onclick = fun ction(){} イベントをキャプチャする予定の関数にイベントリスナーを追加しています。大きな問題ではない! –

答えて

5

他のclickイベントハンドラの中のclickイベントハンドラをbindにする必要はありません。単一のclickイベントハンドラを使用する必要があります。

show/hide機能は、第二clickイベントハンドラに属し、これは最初のclick後にspan DOM要素にbindedです。

function toggleDivFunction() { 
 
    var arrowElement = document.getElementById ("arrowRight"); 
 
    var showElement = document.getElementById ("dropdownText"); 
 
    if(showElement.style.display == 'none') 
 
    { 
 
     showElement.style.display = 'block'; 
 
     document.getElementById("arrowRight").style = "transform: rotate(+90deg)"; 
 
    } 
 
    else 
 
    { 
 
     showElement.style.display = 'none'; 
 
     document.getElementById("arrowRight").style = "transform: rotate(0deg)"; 
 
    } 
 
}
<p class="dropdownHeader">TOP <span id="arrowRight" class="arrowRight" onclick="toggleDivFunction();"> > </span></p> 
 
<div class="dropdownText" id="dropdownText"> 
 
<p>TEXT TO BE SHOWN</p></div>

0

あなたは以前、あなたのイベントハンドラを割り当てる:

window.onload=toggleDivFunction; 

のonclick = 'toggleDivFunction()'、当時とオールド・ファッションドの不必要なを削除します。

イベントがトリガーされたとき(toggleDivFunction)、リスナーを割り当てます。リスナー(arrowElement.onclick)をトリガーするには、をクリックして別のイベントを発生させる必要があります。

0

arrowElement.onclick = function() {}

なぜを削除しますか?あなたはまだない、両方

、onclickの機能のいずれか.USE DomarrowElement.onclickを実行するために、その後toggleDivFunction()を実行する最初の .soがarrowRightonclick=toggleDivFunction()に関数を適用している

関連する問題