【发布时间】:2019-03-30 06:05:53
【问题描述】:
尝试使用 document.createElement() 将 Materializecss 站点中的动态复选框和集合元素插入到我的 html 中(循环中的复选框与我的名字一样多 - 每个名称都应该有自己的复选框)。
我的问题:
1) 它适用于集合,但复选框不会出现在我的侧边栏中(请参阅底部的代码)。
2) 每个复选框是否需要不同的 ID 和 For 属性?
3) 我想使用从复选框和对应名称中获取的值。为此,我必须在此处将名称放在复选框的 <span> 标记中:
<label>
<input type="checkbox" class="filled-in" checked="checked" />
<span>Filled in</span>
</label>
但我想将名称保留在此 Collection 标签中而不是复选框标签中,因为 a) 它看起来很棒 b) 我希望以我现在拥有的方式在名称上添加链接。
<div class="collection">
<a href="#!" class="collection-item">Alvin</a>
</div>
问题是我能否从 2 个不同的元素中读取相应的值?
//collection element from Materializecss site
var collection = document.getElementById("coll")
//form element from Materializecss site
var form = document.getElementById("form")
for (var i = 0; i < names.length; i++) {
//getting each name
var name = names[i]
//creates a label tag for each checkbox
var newLabelTag = document.createElement("LABEL")
newLabelTag.setAttribute("for", "item");
//add item to the mother collection element
form.appendChild(newLabelTag);
//creates a span tag for each checkbox
var newSpanTag = document.createElement("SPAN")
// Add names to it
var Text = document.createTextNode(name);
//new line
var br = document.createElement("BR");
newSpanTag.appendChild(br);
//append the text with names to the tag
newSpanTag.appendChild(Text);
//add item to the mother collection element
form.appendChild(newSpanTag);
//creating a new <input> tag
var newInputTag = document.createElement("INPUT")
//set a class to a new tag
newInputTag.setAttribute("class", "filled-in");
newInputTag.setAttribute("id", "item");
newInputTag.setAttribute("type", "checkbox");
//add item to the mother collection element
form.appendChild(newInputTag);
//creating a new <a> tag (Collection items)
var newATag = document.createElement("A")
//set a class to a new tag
newATag.setAttribute("class", "collection-item");
// add the URL attribute
newATag.setAttribute("href", "https//blah");
// Add names to it
var newText = document.createTextNode(name);
//append the text with names to the tag
newATag.appendChild(newText);
//add item to the mother collection element
collection.appendChild(newATag);
}
【问题讨论】:
-
回答一个问题:ID 在页面上应该是唯一的,所以它不应该重复,甚至不超过一个复选框应该具有相同的 ID。并且“For”属性出现在该复选框的标签上,并且应该与该复选框的 ID 匹配。
-
感谢您的建议。我可以在循环时使用 setAttribute("for", i) 和 setAttribute("id", i) 。有人可以帮忙解决第一个问题吗?)我的代码有什么问题?
-
真正把一个问题限制在一个问题上会更好。
-
你可以看看这篇文章。 stackoverflow.com/questions/1950939/…
-
更新:输入元素有效,当我删除 newInputTag.setAttribute("type", "checkbox") 或 newInputTag.type = "checkbox" 行时,我可以在边栏中看到它。然后我可以将其视为 TEXT INPUT(您可以在其中键入文本的行)!所以它没有收到我说它应该是一个复选框!虽然我使用与网站上相同的措辞。谁知道该怎么做?
标签: javascript html checkbox