简体   繁体   English

在运行时Silverlight 4中动态添加Javascript

[英]Add Javascript Dynamically at Runtime Silverlight 4

I am trying to have a method in my code behind at runtime add a function at runtime. 我试图在运行时的代码中添加一个方法,然后在运行时添加一个函数。 I can dynamically add elements to my document with no problem. 我可以毫无问题地向文档中动态添加元素。 So I tried the same strategy for adding a script block. 因此,我尝试了相同的策略来添加脚本块。

Here's what I have tried thus far with no luck. 到目前为止,这是我一直没有尝试过的方法。 It can create the script block but when I try to add the function. 它可以创建脚本块,但是当我尝试添加功能时。 The only thing I can gather is that since the page is loading, it can't add the JS method. 我唯一可以收集的是,由于页面正在加载,因此无法添加JS方法。 I am trying to add this before the page is loaded. 我试图在页面加载之前添加它。 So I figured I would be able to add script. 所以我认为我可以添加脚本。 If I can't add a function, I would like to at least feed it some javascript in my code behind to invoke at runtime. 如果我无法添加函数,则至少要在我的代码中向其提供一些JavaScript,以便在运行时调用。

Here is how I try to dynamically add the script block... which throw a runtime error on the SetProperty() method. 这是我尝试动态添加脚本块的方式...这会在SetProperty()方法上引发运行时错误。

HtmlElement script = HtmlPage.Document.CreateElement("script");
script.SetAttribute("type", "text/javascript");
script.SetProperty("innerHTML", "function testing() { alert('hello world'); }");
HtmlPage.Document.Body.AppendChild(script);

Then to invoke an EXISTING function on the document this works... 然后在文档上调用EXISTING函数即可。

HtmlPage.Window.Invoke("testing2");

If I can't dynamically add a script block could I somehow invoke some javascript from my code behind? 如果我不能动态添加脚本块,我可以以某种方式从后面的代码中调用一些javascript吗?

Thanks!!! 谢谢!!!

Well I figured out how to Invoke some script from the code behind... 好吧,我想出了如何从背后的代码中调用一些脚本...

Here's how to invoke some script at run-time 这是在运行时调用某些脚本的方法

HtmlPage.Window.Eval("window.close();");

Here is a way to dynamically create JavaScript functions and add them to your page to use in silverlight applications. 这是一种动态创建JavaScript函数并将其添加到页面以在Silverlight应用程序中使用的方法。

// Create the script block
var scriptElement = HtmlPage.Document.CreateElement("script");
scriptElement.SetAttribute("type", "text/javascript");
// Add a function called foo
scriptElement.SetProperty("text", "function foo() { alert('hello foo!'); } ");
// Append script block to the body of the page
HtmlPage.Document.Body.AppendChild(scriptElement);


// Now invoke the function from your silverlight application
HtmlPage.Window.Invoke("foo", null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM