2017-03-21 24 views
0

我試圖讓一個按鈕顯示一個模塊,當它是一個元素有一個子節點時。所以當你點擊它時,它將激活該功能並相應地顯示模式,它將通過將id「myBtn」添加到button元素來實現。更改一個按鈕的功能時獲取未捕獲的參考錯誤

這是我的HTML:

<li id='parentNode'> 
    <button onclick="child_check()" id="button" class='customer-btn'><a href='#'>Customer 6</a></button> 
    <ul> 
    <li id='childNode'> 
     <a href='#'>Customer A</a> 
    </li> 
    </ul> 
</li> 

這是我的JS:

<script> 

    var modal = document.getElementById('myModal'); 
    // Get the button that opens the modal 
    var btn = document.getElementById(" myBtn"); 
    // Get the <span> element that closes the modal 
    var span = document.getElementsByClassName("close")[0]; 
    btn.onclick = function() { 
     modal.style.display = "block"; 
    } 


    // When the user clicks on <span> (x), close the modal 
span.onclick = function() { 
    modal.style.display = "none"; 
    } 
    // When the user clicks anywhere outside of the modal, close it 

// Check to see if the list element has a child 
function child_check() { 
    var child = document.getElementById("childNode"); 
    var parent_check = document.getElementById("parentNode").contains(child); 
    var parent = document.getElementById("parentNode") 
    var button = document.getElementById("button") 
    if (parent_check){ 
    button.id += " myBtn"; 
    // Code that activates modal 
    // Get the modal 

    // When the user clicks on the button, open the modal 

    } 
} 


</script> 

任何幫助嗎?我的方式在這裏下車

編輯:似乎是工作,還是得到以下錯誤:Uncaught TypeError: Cannot read property 'contains' of null at child_check (profile:259)

+2

'它會通過在按鈕元素中添加id「myBtn」來實現 - 實際上它會將id從'parentNode'改爲'parentNodemyBtn' - 如果只有'getElementById'是一個函數 - 你的意思是'document .getElementById'也許 –

+1

@JaromandaX對你的id調整是正確的 - 你可能想要'='而不是'+ ='。另外:「並相應地顯示模式,它會通過將ID」myBtn「添加到按鈕元素」 - 你是否斷言簡單地向元素添加ID會啓動模式?因爲這聽起來不對...... –

+0

@JaromandaX嘿,抱歉,對於遲到的答覆,謝謝我甚至沒有意識到我引用了id,而不是實際的元素。我只是想一個新的ID添加到父元素 – Amon

回答

1

模態一邊(我在這裏看到沒有模態代碼),你也許可以添加一個空格您+= " myBtn"像這樣行,成功地給這個按鈕一個ID'myBtn'。如果沒有,只需使用一個普通的「=」,並給它所需的所有ID,用空格分隔。

+0

我更新了我的問題與模態代碼問題 – Amon

+1

據我所知,parentNode不是一個變量。您嘗試引用它,但沒有在任何地方定義它。另外,當你設置parentNode.id時,如果你給它的是1個ID,那麼你不需要空間。如果它已經有一個ID,並且您想給它另一個ID,那麼您可以使用+ =並在該ID前添加一個空格,以便知道新ID與您要添加的ID是分開的。換句話說,讓它說'id =「oldID newID」'而不是'id =「oldIDnewID」' – Bango

+0

你是指當我在參數中引用它嗎?這不是你應該如何使用該功能? – Amon

相關問題