简体   繁体   English

从Silverlight 4.0应用程序调用JavaScript函数

[英]Call JavaScript function from Silverlight 4.0 application

I am trying to call a function from a Silverlight application. 我正在尝试从Silverlight应用程序调用函数。 It should be a very simple task to do but so far I am not getting the result that I am looking for. 这应该是一个非常简单的任务,但是到目前为止,我没有得到想要的结果。

This is my Silverlight code: 这是我的Silverlight代码:

    private void button2_Click(object sender, RoutedEventArgs e)
    {
        HtmlPage.Window.Invoke("SayHello", new string[] { "Salut!" });
    }

And this is the JavaScript code : 这是JavaScript代码:

   function SayHello(theid) {
        alert(eval(theid));
        var divStatusDiv = document.getElementById("divStatus");
        divStatusDiv.style.backgroundColor = "Red";
    }

The alert message always show "undefined" but when I press "OK" the colour of that DIV gets changed to Red as it should be. 警报消息始终显示为“未定义”,但是当我按“确定”时,该DIV的颜色将变为应有的红色。

Why am I getting "Undefined" all the time ? 为什么我一直都处于“未定义”状态?

You need to create the json that can be passed properly instead of just passing along an array like that. 您需要创建可以正确传递的json,而不是仅传递这样的数组。 You can simply return "Salut!" 您可以简单地返回“ Salut!” instead of new string[] { "Salut!" 而不是新的字符串[] {“ Salut!” } or you can create the json array for the string array you have. },也可以为您拥有的字符串数组创建json数组。

I'm not familiar with Silverlight, but if theid has value "Salut!" 我对Silverlight不熟悉,但是如果该theid价值是"Salut!" inside of SayHello , then you cannot eval it, since it is a string of text, not code. SayHello内部,则无法eval它,因为它是文本字符串,而不是代码。 You should change the line alert(eval(theid)); 您应该更改行alert(eval(theid)); to just alert(theid); 只是alert(theid); .

采用

alert(eval(theid.value));

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

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