首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

dom小疑点,setAttribute(.)第二个参数怎么调用函数

2013-10-10 
dom小问题,setAttribute(..,..)第二个参数如何调用函数?小程序目的:在页面创建一个按钮,按此按钮调用creat

dom小问题,setAttribute(..,..)第二个参数如何调用函数?
dom小疑点,setAttribute(.)第二个参数怎么调用函数

小程序目的:在页面创建一个按钮,按此按钮调用createNewButton()函数创建一个新的按钮,按新的按钮调用show()函数在页面显示“new button content..."。
实际创建新按钮后创建属性setAttribute("onclick","show()"),使用ie浏览器打开,显示新按钮的onclick属性不起作用,为什么?如利用setAttribute创建的属性调用其他函数,应如何写?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>attrTest</title>
<script>
    function createNewButton(){
        var body=document.getElementById("body");
        var newBtn=document.createElement("input");
        newBtn.setAttribute("type","button");
        newBtn.setAttribute("value","show text");
        newBtn.setAttribute("onclick","show()");//此句似乎在ie浏览器不起作用,无法调用show()函数
        body.appendChild(newBtn);
    }
    
    function show(){
        document.getElementById("txt").innerHTML="new button content....";
    }
</script>
</head>
<body id="body">
<p id="txt">new button text show here</p>
<input type="button" onclick="createNewButton()" value="Create new button"/>
</body>
</html>
[解决办法]
newBtn.onclick = show;//ie浏览器要这样写
[解决办法]

引用:
Quote: 引用:

newBtn.setAttribute("onclick",show)

谢谢,通过了。
我试过newBtn.setAttribute("onclick",show());不行,为什么去掉()就可以了,还请再多指教一点。



function a (){ alert(1) }

var s = a;
var s = a();

你觉得区别在那里呢?
[解决办法]
函数带参数必须这样

热点排行