<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<script type="text/javascript">
function test()
{
var _LI=document.getElementById("myLI");
var liImg=document.createElement("img");
liImg.style.width="152px";
liImg.style.height="152px";
liImg.src="......";
liImg.setAttribute("onclick",clickTest(liImg))
_LI.appendChild(liImg);
}
function clickTest(obj)
{
alert(obj.src);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<ul id="myUL">
<li id="myLI"></li>
</ul>
<input type="button" value="添加元素" onclick="test()"/>
</div>
</form>
</body>
</html>
<head runat="server">
<title>无标题页</title>
<script type="text/javascript">
function test()
{
var _LI=document.getElementById("myLI");
var liImg=document.createElement("img");
liImg.style.width="152px";
liImg.style.height="152px";
liImg.src="......";
liImg.setAttribute("onclick",clickTest(liImg))
_LI.appendChild(liImg);
}
function clickTest(obj)
{
alert(obj.src);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<ul id="myUL">
<li id="myLI"></li>
</ul>
<input type="button" value="添加元素" onclick="test()"/>
</div>
</form>
</body>
</html>
然后放到你要放到地方去
为什么我没有显示调用创建的元素的onclick方法,它自动调用了呢????
innerHTML += "<img>...</img>"
{
var _LI=document.getElementById("myLI");
var liImg=document.createElement("img");
liImg.style.width="152px";
liImg.style.height="152px";
liImg.src="......";
liImg.attachEvent('onclick',function(){clickTest(liImg)});
_LI.appendChild(liImg);
} 这样写
这样写也行。。不带参数就这么写
liImg.setAttribute('onclick',clickTest); 具体区别问google