English 中文(简体)
如何在javascript中添加onclick事件来创建新元素
原标题:how to add onclick event to create new element in javascript
  • 时间:2011-05-27 18:14:53
  •  标签:
  • javascript

我已经创建了一个标签元素。我需要添加<code>onclick</code>事件。。。

function a(me) {
    var d=document.createElement("label");
    d.id=me.id;
    d.onClick="a(10)";
    d.innerHTML="welcome";
    document.body.appendChild(d);
}

HTML:

<label id="1" onclick="a(this)">aa</label>
<label id="2" onclick="a(this)">bb</label>
<label id="3" onclick="a(this)">aa</label>

实际上,当我点击html中的三个标签中的任何一个时,都会发生这种情况。创建另一个标签并显示欢迎。现在,当我点击新创建的标签“欢迎”时,它不会显示任何内容。。。。。。也就是说,添加到新创建的标签中的onclick事件不起作用。。。。。。。任何建议。。。。。。。。。。。。。。。。。

最佳回答

您需要设置<code>d.onclick=function(){a(1);},注意这里的情况很重要(而不是“onClick”)。

[编辑]

根据您的评论和更新的问题,我创建了一个jsFiddle演示如何将代码转化为有效的东西。

问题回答
d.setAttribute( onclick ,  alert( hello ); );

为了创建HTML标记的属性,有时我们必须添加以下内容:

yourTag.src
yourTag.src =  http://lolxd.com/404.png 

但也有一些特殊的属性,它们有不同的编辑方式:

yourTag.classList
yourTag.className

还有onclick属性,wichwe可以这样使用它:

// The first way
obj.onclick = function () { alert( lalala ) }
// With the Event Listener
obj.addEventListener( click , function () { alert( lalala ) }, false)
// Or, a text-render way
obj.setAttribute( onclick ,  alert(`lalala`) )

我建议您使用事件侦听器的方式,但请全部尝试:D





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签