Javascript 处理第二个按钮而不是第一个

标签 javascript html css

我有一个表格,我试图通过单击按钮来显示和激活其中的表格信息。表格设置为“显示:无”,按钮连接到 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/

相关文章:

javascript - 如何保证一些内容总是堆叠在主要内容的后面

javascript - Toastr 通知未显示在右下角

css - svg 笔划文本在 foreignObject 中不起作用

javascript - meteor 在 onrendered 模板中调用 jquery

javascript - 如何在有序列表中定位数组的特定部分

javascript - 当创建两个以上的球时, Canvas 中的弹跳球会表现出奇怪的行为

javascript - HTML 文本区域防止某些文本被删除

html - 边框无法在链接 html 上正常工作

javascript - 嵌套的 If/Else 比 Else If 有什么优势吗?

javascript - ng-animate 不适用于 animate.css