这是我昨天问过的question的后续行动。
我有一个用户脚本(有点像GreaseMonkey脚本,但对于Chrome)。
这个想法是在页面上添加一个文本框和一个按钮。然后,当用户单击该按钮时,它将启动一个执行操作的功能。所以我将文本框,按钮和功能注入页面,但是当用户点击按钮时,Chrome控制台会告诉我“未捕获的TypeError:对象不是函数”。所以显然它没有看到我刚刚注入的函数,并且在按钮的onclick
事件中指定了该函数。
所以我有这样的代码:
initialize();
function initialize() {
var dropDown = document.getElementById("tstGlobalNavigation_ddlChooseProject");
// add a textbox
dropDown.innerHTML = dropDown.innerHTML + " <input type='text' name='txtSearch' style='position:absolute;top:8px;left:800px;width:50px' >";
// add a button
dropDown.innerHTML = dropDown.innerHTML + " <input type='button' name='btnSearch' value='Go' onclick='fn()' style='position:absolute;top:8px;left:860px;width:35px'>";
addScript("var obj = document.getElementById('txtSearch'); "
+ "if (obj != null) { "
+ " var incidentId = document.getElementById('txtSearch').value; "
+ " var currentURL = location.href; "
+ " var splitResult = currentURL.split('/'); "
+ " var projectId = splitResult[4]; "
+ " location.href = 'http://dev.myApp.com/ProductTeam/' + projectId + '/Incident/' + incidentId + '.aspx'; "
+ " }"
, "fn");
}
function addScript(contents, id) {
var head, script;
head = document.getElementsByTagName('head')[0];
script = document.getElementById(id);
if(script != undefined) {
head.removeChild(script);
}
script = document.createElement('script');
script.type = 'text/javascript';
script.id = id;
script.innerHTML = contents;
head.appendChild(script);
}
我在这里缺少什么?
答案 0 :(得分:2)
您没有调用您创建的函数,而是使用您为脚本标记提供的ID ...尝试将代码更改为
addScript("function fn() { var obj = document.getElementById('txtSearch'); "
+ "if (obj != null) { "
+ " var incidentId = document.getElementById('txtSearch').value; "
+ " var currentURL = location.href; "
+ " var splitResult = currentURL.split('/'); "
+ " var projectId = splitResult[4]; "
+ " location.href = 'http://dev.myApp.com/ProductTeam/' + projectId + '/Incident/' + incidentId + '.aspx'; "
+ " } }"
, "fn");
你将拥有一个可以被称为
的fn()函数答案 1 :(得分:1)
问题在于您尝试使用onclick
元素属性绑定事件处理程序。这些属性仅在首次加载页面时进行解析,此时您尝试绑定的函数作为回调不存在。
尽可能避免在元素on*
属性中绑定事件处理程序。这称为写作unobtrusive JavaScript。
那就是说,如果你绝对必须坚持使用onclick
,你可以绑定到一个虚拟函数,它除了转身并调用你注入的函数之外什么都不做:
<button onclick="wrapper()"
wrapper
看起来像这样:
function wrapper() {
return functionThatWillEventuallyBeInjected();
}
答案 2 :(得分:-1)
我不确定您是否可以实时创建script
代码并推送内容。
您可以改为创建脚本标记并将src属性修改为某个JS文件:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "path/to/your/javascript.js";
document.body.appendChild(script);
如果你真的需要执行存储在字符串中的代码,可能只需要eval()
就可以了!