2017-10-16 4 views
0

switchVisible関数を使用して純粋なJavaScriptを使用しようとしています。私は現在、getElementByIdを使って作業していますが、ボタンをクリックしたときに表示および非表示にする要素が複数あります。function switchVisibleをクラス名で使用する方法は?

CSS

#unlocked { 
    display: none; 
} 

HTML

<input id="edit-invoice" type="button" value="Edit Invoice" onclick="switchVisible();" /> 

<p id="locked" class="locked">anexample.pdf</p> 
<input id="unlocked" class="unlocked" type="text" placeholder="anexample.pdf"> 

これは、これまでに動作しますが、それはIdであるので、それが唯一の要素をターゲットにすることができ

function switchVisible() { 
    if (document.getElementById('locked')) { 
     if (document.getElementById('locked').style.display == 'none') { 
      document.getElementById('locked').style.display = 'inline-block'; 
      document.getElementById('unlocked').style.display = 'none'; 
     } 
     else { 
      document.getElementById('locked').style.display = 'none'; 
      document.getElementById('unlocked').style.display = 'inline-block'; 
     } 
    } 
} 

のように今の私のjavascriptが見えます。どのように私はこのスクリプトを取ってクラス名で要素をターゲットにできるように変更することができますので、ボタンクリックで複数の要素を非表示にすることができますか?

答えて

0

あなたは使用getElementsByClassNameクラス名で

function switchVisible() { 
 

 
    // Get locked and unlocked elements by class name 
 
    let lockedElems = document.querySelectorAll(".locked"); 
 
    let unlockedElems = document.querySelectorAll(".unlocked"); 
 

 
    // Loop through locked elements 
 
    Array.prototype.map.call(lockedElems, function(locked, index) { 
 
    
 
    // Get current unlocked element 
 
    let unlocked = unlockedElems[index]; 
 
    
 
    // Do your thing 
 
    if (locked) { 
 
     if (locked.style.display == "none") { 
 
     locked.style.display = "inline-block"; 
 
     unlocked.style.display = "none"; 
 
     } else { 
 
     locked.style.display = "none"; 
 
     unlocked.style.display = "inline-block"; 
 
     } 
 
    } 
 
    
 
    }); 
 
}
.unlocked { 
 
    display: none; 
 
}
<input id="edit-invoice" type="button" value="Edit Invoice" onclick="switchVisible()" /> 
 

 
<p class="locked">anexample.pdf</p> 
 
<input class="unlocked" type="text" placeholder="anexample.pdf"> 
 

 
<p class="locked">anexample.pdf</p> 
 
<input class="unlocked" type="text" placeholder="anexample.pdf"> 
 

 
<p class="locked">anexample.pdf</p> 
 
<input class="unlocked" type="text" placeholder="anexample.pdf">

0

を複数の要素をターゲットとし、その結果をループすることができます。

function switchVisible() { 
    var locked = getElementsByClassName('locked'); 
    for (var i = 0; i < locked.length; i++) { 
     if (locked[i].style.display == 'none') { 
      document.getElementById('locked').style.display = 'inline-block'; 
      locked[i].nextElementSibling.style.display = 'none'; 
     } 
     else { 
      locked[i].style.display = 'none'; 
      locked[i].nextElementSibling.style.display = 'inline-block'; 
     } 
    } 
} 
関連する問題