Kar*_*das 3 javascript code-generation
我想要实现的很简单:按下按钮时,它会创建一个带选项的选择元素.我可以做精选元素,但选项,而不是.我尝试了很多东西.这是我使用的代码,有一些注释可以提供帮助.
<!--This is the element that we append the JavaScript to. The code that achieves the task is at the bottom.-->
<p id="clonePanel"></p>
<script>
//Don't worry about the first pid stuff.
var pid = 0;
function dupPan() {
pid++;
//Here we create a "p" element. The following code is the element's content and specs.
var newPanel = document.createElement("p");
newPanel.id=pid;
//Here we create a "select" element (a drop down list).
var newList = document.createElement("select");
//Here we create a text node.
var newListData = document.createTextNode("Example of option");
//Here we append that text node to our drop down list.
newList.appendChild(newListData);
//Here we append our list to our "p" element.
newPanel.appendChild(newList);
//Finally, we append the "p" element to the document, or the "clonePanel" p element.
document.getElementById("clonePanel").appendChild(newPanel);
}
</script>
Run Code Online (Sandbox Code Playgroud)
希望评论有所帮助.应该发生的是选择元素与文本节点一起生成.然后将两者附加在一起.最后,将所有内容附加到ap元素,最后将其放入文档中.我知道我做错了什么.
我认为我创建文本节点的方法不正确.我认为还有别的东西.如果您知道答案,请告诉我正确的代码行?那太好了.是的,我已经看过任何可以寻求帮助的消息来源,但无济于事.
感谢您阅读并帮助我!
您将文本节点附加到选择,这是不对的.您应该添加一个选项:
var newListData = new Option("my label", "my value");
//Here we append that text node to our drop down list.
newList.appendChild(newListData);
Run Code Online (Sandbox Code Playgroud)
您可以将Option
上面的类似实例化为快捷方式,或者您可以使用document.createElement('option')
它来做很长的事情.
可以通过丢失变量并直接添加新选项来进一步简化:
newList.appendChild(new Option("my label 1", "my value 1"));
newList.appendChild(new Option("my label 2", "my value 2"));
newList.appendChild(new Option("my label 3", "my value 3"));
Run Code Online (Sandbox Code Playgroud)