Javascript在第二个按钮单击而不是第一个按钮上工作

Javascript working on second button click instead of first

本文关键字:按钮 第一个 工作 第二个 单击 Javascript      更新时间:2023-09-26

我有一个表格,我正在尝试通过单击按钮来显示和激活表单信息。该表设置为"display: none",按钮连接到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方法没有参数。它不会查找和删除元素。