简体   繁体   English

JavaScript 函数在表单循环中不起作用

[英]JavaScript function doesn't work in form loop

JavaScript work only in first iteration, doesn't affect on the field from second iteration. JavaScript 只在第一次迭代中工作,不会影响第二次迭代的领域。

forloop Code Sample forloop 代码示例

 {% for i in userlist %}
    <input id="a" type="email" value="{{i.email}}">
    <input id="b" type="text" value="{{i.date_of_birth}}">
    <input id="c" type="text" value="{{i.mobile}}">
 {% endfor %}

Button for disable editing用于禁用编辑的按钮

<button onclick="disableProfileEditing()" type="button"> Disable </button>

Button for enable editing用于启用编辑的按钮

<button onclick="enableProfileEditing()"> Edit</button>

JavaScript function JavaScript 函数

function disableProfileEditing() {
    document.getElementById(a).disabled = true;
    document.getElementById(b).disabled = true;
    document.getElementById(c).disabled = true;
}


function disableProfileEditing() {
    document.getElementById(a).disabled = false;
    document.getElementById(b).disabled = false;
    document.getElementById(c).disabled = false;
}

Ok regardless of how the for loop is made, what it is doing is making many elements with the same I'd, which is a problem.好的,不管 for 循环是如何制作的,它所做的是制作许多具有相同 Id 的元素,这是一个问题。 Instead you can give them all a unique class, or data attribute, but class is simpler and more widely supported, then in your function you have to get all elements with that class (or data attribute) and do the hiding etc.相反,您可以为它们提供一个唯一的类或数据属性,但类更简单且支持更广泛,然后在您的函数中,您必须获取具有该类(或数据属性)的所有元素并进行隐藏等。

So for the for loop所以对于 for 循环


 {% for i in userlist %}
    <input  class="email" type="email" value="{{i.email}}">
    <input class="dob" type="text" value="{{i.date_of_birth}}">
    <input class="mobile" type="text" value="{{i.mobile}}">
 {% endfor %}

Just changed the IDs to class, so you can have more than one.只是将 ID 更改为类,因此您可以拥有多个 ID。 Now for the first function just get all of each class (and the second one I'll leave for you to figure out)现在对于第一个函数,只需获取每个类的所有内容(第二个我将留给您弄清楚)

function disableProfileEditing() {
    Array.apply(0,document.getElementsByClassName("email")).forEach(x=> x.disabled = true);
    Array.apply(0,document.getElementsByClassName("dob")).forEach(x=> x.disabled = true);
    Array.apply(0,document.getElementsByClassName("mobile")).forEach(x=> x.disabled = true);
}

OR you could have just made a surrounding container div with a unique ID then just made the for loop add elements into that, probably would have been simpler if you want to show or hide them all together或者,您可以创建一个具有唯一 ID 的周围容器 div,然后让 for 循环向其中添加元素,如果您想将它们一起显示或隐藏,可能会更简单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM