表未附加到我的 html 中的特定 div 'contactsearchtable'



我正在创建一个表,我希望能够将其放置在我的HTML代码中的特定div元素点。我总是得到"未捕获的TypeError: tableSpot"。Append不是一个函数在XMLHttpRequest.xhr.onreadystatechange"在

tableSpot.appendChild(table);

我不确定我做错了什么。注释掉的

// document.body.appendChild(table);

成功地添加到我的文档中,但我希望能够隐藏或显示表,这就是为什么我希望它在div元素中。

我已经附加了一部分的js设置和"创建"表,我的HTML的一部分,我想要它去。-我不认为这是有多大的相关性,但displayChange('div1', 'div2')只是一个函数,改变'div1'显示的风格从无块,反之亦然'div2'。有点离题了,但它只适用于HTML。当我试图从js代码调用它时,我遇到了另一个错误。——

var table = document.createElement('table'),
thead = document.createElement('thead'),
tbody = document.createElement('tbody'),
th,
tr,
td;
th = document.createElement('th'),
th.innerHTML = "id";
table.appendChild(th);
th = document.createElement('th');
th.innerHTML = "First Name";
table.appendChild(th);
th = document.createElement('th');
th.innerHTML = "Last Name";
table.appendChild(th);
th = document.createElement('th');
th.innerHTML = "Phone Number";
table.appendChild(th);
th = document.createElement('th');
th.innerHTML = "Email";
table.appendChild(th);
table.appendChild(thead);
table.appendChild(tbody);
var tableSpot = document.getElementById('contactSearchResult').outerHTML;
tableSpot.appendChild(table);
// document.body.appendChild(table);
<div id="searchBox" style="display: none">
<input type="text" id="searchText" onkeyup="doSearch();displayChange('contactSearchDiv', 'searchBox');" placeholder="Please Type or hit Enter" />
</div>
<div id="contactSearchDiv" style="display: none">
<span id="contactSearchResult"></span>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
<button type="button" id="editFromSearch" style="display:block" onclick="displayChange('editContactDivForm', 'contactSearchDiv');">
Edit Contact </button><br/>
<button type="button" id="deleteFromSearch" style="display:block" onclick="displayChange('deleteDiv', 'contactSearchDiv');">
Delete Contact </button><br/></br>
<div id="searchList">
</div><br /><br/>

只是为了帮助你有一个更好的开始…

const
btShowHide    = document.getElementById('bt-show-hide')
, contactSearch = document.getElementById('contactSearchDiv')
, myTable       = document.createElement('table')
, myThead       = myTable.createTHead()
, myTbody       = myTable.createTBody()
;
let newRow = myThead.insertRow()
newRow.insertCell().textContent = 'id'
newRow.insertCell().textContent = 'First Name'
newRow.insertCell().textContent = 'Last Name'
newRow.insertCell().textContent = 'Phone Number'
newRow.insertCell().textContent = 'Email'
contactSearch.appendChild(myTable)
btShowHide.onclick = evt =>
{
contactSearch.classList.toggle('noDisplay')
}
* {
font-family : Arial, Helvetica, sans-serif;
font-size   : 14px;
}
.noDisplay {
display : none;
}
table  {
border-collapse : collapse;
margin          : 1em;
}
td {
padding : .2em .8em;
border  : 1px solid darkblue;
}
thead { 
background : lightsteelblue;
}
<button id="bt-show-hide">show / hide</button>
<div id="contactSearchDiv" class="noDisplay"> </div>

最新更新