我有一个表格,我试图通过单击按钮来显示和激活其中的表格信息。表格设置为“显示:无”,按钮连接到 javascript。 javascript 有效,但仅在第二次单击按钮后有效。我希望它在第一次被点击时工作。
按钮和表格 HTML:
<button data-bind="click: addPatient" style="margin-top: 20px; margin-bottom: 10px;">Add Patient</button>
<table id="newPatientForm">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th></th>
</tr>
<tbody data-bind="foreach:Patients">
<tr>
<td class="form-group"><input data-bind="value: FirstName, event: {change: flagPatientAsEdited}, hasfocus: true" /></td>
<td class="form-group"><input data-bind="value: LastName" /></td>
<td class="form-group"><button data-bind="click: $parent.removePatient">Delete</button></td>
</tr>
</tbody>
</table>
这是表格 CSS:
#newPatientForm {
display: none;
}
这是按钮调用的 javascript。
self.addPatient = function () {
var divElement = document.getElementById('newPatientForm');
var patient = new PatientViewModel({ SiteId: 0, FirstName: "", LastName: "", ObjectState: ObjectState.Added });
if (divElement.style.display == 'none') {
divElement.style.display = 'block';
self.Patients.push(patient);
}
else {
divElement.style.display = 'none';
self.Patients.pop(patient);
}
},
最佳答案
在样式表中设置时需要检查计算样式
function isHidden(elem) {
var style = window.getComputedStyle(elem);
return style.display === "none";
}
改变
if (divElement.style.display == 'none') {
到
if (isHidden(divElement)) {
使用了上面的方法。
最好只拥有一个隐藏或不隐藏的类并切换该类。
最后,我不认为 self.Patients.pop(patient);
正在做您认为正在做的事情。 pop
方法没有参数。它不查找和删除元素。
关于Javascript 处理第二个按钮而不是第一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28073059/