[英]Creating a Label Dynamically using Javascript
I am using Aspnet, and i need to create an undetermined number of labels for one specific page. 我正在使用Aspnet,并且我需要为一个特定的页面创建数量不确定的标签。 I have a button that calls a function which generates a label dynamically using javascript:
我有一个按钮,该按钮调用使用javascript动态生成标签的函数:
<script type="text/javascript"> function create() { var newlabel = document.createElement("box1"); ... document.getElementById("MainContent_revenuestreams").appendChild(newlabel); } </script>
What happens is that after the label is created he only shows on the webpage for about 2-3 seconds and after that it disapears (i think that the postback eliminates its content). 发生的情况是,在创建标签后,他只在网页上显示了2-3秒,然后消失了(我认为回发消除了其内容)。
I would like to know how can i avoid this 我想知道如何避免这种情况
document.createElement(type)
- type
must be a html tag name like: div, table, p. document.createElement(type)
type
必须是html标记名称,例如:div,table,p。
In your case: 在您的情况下:
var newLabel = document.createElement("label");
Then you set attributes for this element ( for
- most important in label, id, name). 然后,您可以为此元素设置属性(
for
-在标签,ID,名称中最重要)。
Finally: 最后:
newLabel.appendChild(document.createTextNode("This is where label caption should be"));
document.getElementById("MainContent_revenuestreams").appendChild(newLabel);
Some links: 一些链接:
http://www.w3schools.com/jsref/met_document_createelement.asp http://www.w3schools.com/jsref/met_document_createelement.asp
http://www.w3schools.com/jsref/met_document_createtextnode.asp http://www.w3schools.com/jsref/met_document_createtextnode.asp
As you see box1
is not a valid argument for document.createElement(type)
. 如您所见,
box1
不是document.createElement(type)
的有效参数。
You have to return false to cancel the postback of the button: 您必须返回false才能取消按钮的回发:
<asp:Button runat="server" OnClientClick="javascript: create();return false;"/>
Also note that document.createElement("box1");
还要注意
document.createElement("box1");
will create a <box1></box1>
element which is probably not what you want. 将创建一个
<box1></box1>
元素,可能不是您想要的。 You should change "box1"
to "label"
or "span"
您应该将
"box1"
更改为"label"
或"span"
Add OnClientClick="addNewlabel();return false;" 添加OnClientClick =“ addNewlabel();返回false;”
function addNewlabel() { 函数addNewlabel(){
var NumOfRow++;
var mainDiv=document.getElementById('MainDiv');
var newDiv=document.createElement('div');
newDiv.setAttribute('id','innerDiv'+NumOfRow);
var newSpan=document.createElement('span');
newSpan.innerHTML="Your Label Name";
// append the span
newDiv.appendChild(newSpan);
mainDiv.appendChild(newDiv);
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.