Javascript 如何将脚本添加到iframe,然后添加元素以触发它
(使用jquery或仅使用js) 是否可以将脚本添加到iframe,然后添加一个元素来触发它?这添加了脚本,但它在Chrome中给了我一个错误,表示函数未定义Javascript 如何将脚本添加到iframe,然后添加元素以触发它,javascript,jquery,iframe,dynamic,insert,Javascript,Jquery,Iframe,Dynamic,Insert,(使用jquery或仅使用js) 是否可以将脚本添加到iframe,然后添加一个元素来触发它?这添加了脚本,但它在Chrome中给了我一个错误,表示函数未定义 //create element var cloned = $("<input type='button'/>") cloned.attr('onclick', "alertUser()"); var parent = $("#parent");
//create element
var cloned = $("<input type='button'/>")
cloned.attr('onclick', "alertUser()");
var parent = $("#parent");
var iframe = $('<iframe />').attr("id", "rbm_pu");
parent.append(iframe);
var frame = $("#rbm_pu").contents();
frame.find("body").append(cloned);
frame.find('body').append("<script type='text/JavaScript'>function alertUser(){alert('hello');}</script>");
//创建元素
变量克隆=$(“”)
克隆的.attr('onclick','alertUser()');
var parent=$(“#parent”);
变量iframe=$('').attr(“id”,“rbm_pu”);
parent.append(iframe);
var frame=$(“#rbm_pu”).contents();
frame.find(“body”).append(克隆);
frame.find('body').append(“函数alertUser(){alert('hello');}”);
它出现在那里,但表示
alertUser()
未定义。有什么想法吗?谢谢这把小提琴会指引你正确的方向:
//首先,创建按钮并分配回调
var按钮=$(“”);
按钮。单击(函数(){
警惕(“你好”);
});
//然后,将按钮附加到新创建的iframe
$('')
.appendTo(“#父项”)
.contents().find('body')
.附加(按钮);
如果您坚持将函数定义为字符串(我强烈建议您不要这样做),这是可行的:
(从和中获取了一些信息)代码有很多地方出错。首先,不要使用attr添加事件处理程序!如果答案是正确的,就结束吧…帕维尔,我真是太感谢你了,兄弟。感谢您传授知识并不断分享!
<div id='parent'></div>
// first, create button and assign the callback
var button = $("<input type='button' value='click me' />");
button.click(function() {
alert("hello");
});
// then, append the button to the freshly created iframe
$('<iframe id="someId"/>')
.appendTo('#parent')
.contents().find('body')
.append(button);