onclick无效。无论何时我提交它都会自动执行所有onclick处理程序

时间:2013-02-07 14:49:58

标签: dom javascript-events

这是代码: HTML + js的

<input type="submit" onclick="chk();" />
function chk(){
var buttonnode= document.createElement('input');
buttonnode.onClick = ddiv(buttonnode);
}

buttonnode.onclick会自动调用ddiv函数,但我希望它等待点击进入该功能。怎么做?

2 个答案:

答案 0 :(得分:0)

尝试如下......它会起作用..

buttonnode.onclick = function (){ddiv(this);};

答案 1 :(得分:0)

尝试如下......它会给出你需要的结果......

<html>
<body>
<style>
.divstyle
{
border: 1px solid red;
}
</style>
<script>

function myFunction()
{

var txt = document.getElementById("txtinfo");

//div Creation
var myDiv = document.createElement("div");
myDiv.setAttribute("class", "divstyle");
myDiv.innerHTML = "<br>" + txt.value + "<br>";

//Button Creation
var myButton = document.createElement("input");
myButton.type = "button";
myButton.value = "my button";
myDiv.appendChild(myButton);
document.body.appendChild(myDiv);
myButton.onclick = function (){ddiv(this,myDiv);};

}

function ddiv(btn, div)
{ 
div.parentNode.removeChild(div);
} 

</script>


<button onclick="myFunction()">Try it</button>
<input type="text" value="Click the Below Button" id="txtinfo"/>
</body>
</html>