我必须通过javascript将下面这行html注入到文档中:
<button type='button'>btnName </button>
除此之外,我还必须将onclick注册到要调用的函数所在的按钮上,该按钮需要一个arg,即'arg'
,因此javascript如下所示:
var html = "<button type='button' onclick='+ fnName +
"(the param shld go here)'>" + btnName + "</button>"
我该如何实现这一点?一个显而易见的解决方案是为按钮分配一个Id,然后在将html附加到文档之后注册一个click函数。但我不想这样做,因为有太多的按钮。你能想到另一种选择吗。
添加:函数名是动态的,其中的'arg'
也是动态的。如果需要,则必须自动生成Id。
**
我已经有了解决方案,请看下面
**
发布于 2009-12-19 14:58:44
我已经有了解决方案:
var html = "<button type='button' onclick='"+ fnName +"("+ JSON.stringify(data) +")'>"+ btnName + "</button>"
发布于 2009-12-19 14:18:56
我推荐jquery。
就像这样
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script>
$(document).append(
$("input")
.attr("type", "button")
.click(function(){
doSomething()
))
);
</script>
发布于 2009-12-19 17:07:55
您应该避免将onclick
用作HTML属性。相反,可以通过DOM接口以编程方式创建按钮,并将事件作为属性附加。
var button = document.createElement("button");
button.type = "button";
button.innerHTML = btnName;
button.onclick = function() {
window[fnName](data);
};
// Insert the button into whatever container node you are populating
someContainerNode.appendChild(button);
或者是jQuery的方式,因为这是乐队的发展方向:
$("<button type='button'>" + btnName + "</button>").click(function() {
window[fnName](data);
}).appendTo(someContainerNode);
此外,由于没有将onclick
处理程序设置为字符串,因此不需要将函数参数data
转换为JSON字符串,这将提高性能。
https://stackoverflow.com/questions/1932131
复制相似问题