我試圖讓一個按鈕顯示一個模塊,當它是一個元素有一個子節點時。所以當你點擊它時,它將激活該功能並相應地顯示模式,它將通過將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)
'它會通過在按鈕元素中添加id「myBtn」來實現 - 實際上它會將id從'parentNode'改爲'parentNodemyBtn' - 如果只有'getElementById'是一個函數 - 你的意思是'document .getElementById'也許 –
@JaromandaX對你的id調整是正確的 - 你可能想要'='而不是'+ ='。另外:「並相應地顯示模式,它會通過將ID」myBtn「添加到按鈕元素」 - 你是否斷言簡單地向元素添加ID會啓動模式?因爲這聽起來不對...... –
@JaromandaX嘿,抱歉,對於遲到的答覆,謝謝我甚至沒有意識到我引用了id,而不是實際的元素。我只是想一個新的ID添加到父元素 – Amon