-1

我尝试使用 javascript 向用户显示一条消息。我有一个按钮,这个按钮的作用类似于,

Label1.Text = "Hello world";
//javascript code

首先,label1.text 将在用户看到消息后显示“Hello world”。

谢谢。

4

5 回答 5

2

C# 和 javascript 代码在不同的时间范围和不同的计算机上运行。您的服务器端代码运行并生成 HTML,然后将其发送到浏览器。然后浏览器运行 javascript 代码。

因此,您不能在 C# 中设置标签文本然后运行 ​​javascript。您不能从 C# 或 C# 从 javascript 中“调用”javascript。

但是,您可以做的是在 javascript 中设置标签文本(在浏览器中呈现为跨度),然后执行您想做的其他事情。

于 2009-10-06T18:06:39.573 回答
1

If I understand you, you need an event handler on the button.

<button id="somebutton">Click me</button>
<label for="someid"></label>

The button can be any html, I just want to show the id, actually.

document.getElementById('somebutton').onclick = function() {
  document.getElementById('someid').innerHTML = 'Hello World';
  return false;
};

You can also just append a child to the label adding a textnode, if you wanted.

于 2009-10-06T17:47:35.913 回答
1

Not sure exactly what you are asking here. I am not aware of a an HTML label. If you are speaking of an ASP:Label, that is rendered as a span in the browser. To set the value in JavaScript, you should access it using the document model. Below might help, if not, please try to clarify your question.

<HTML>

<head>
<script>
function changeText()
{
   document.getElementById('spnSayHello').innerHTML = 'Hello World';
}
</script>
</head>

<body>
<span id='spnSayHello' onclick="changeText();">clickme</span>
</body>
</HTML>

UPDATE: If I understand you correctly, you are trying to render javascript to the page via your c# code? You can do this in a number of ways. The way that I usually do this is using RegisterStartupScript like this:

private void writeSomeJs()
{
   ClientScript.RegisterStartupScript(this.form1.getType(),"jPopUp","<script>alert('Hello World');</script>")
}
于 2009-10-06T17:51:02.323 回答
1

设置标签文本后执行 JavaScript 代码的最简单方法可能如下:

Label1.Text = "Hello world" +
    @"<script type=""text/javascript"">
          alert(""Message to show."");
      </script>";

基本上,JavaScript 代码放置在标签的文本中。当浏览器加载服务器返回的页面时,它会处理 JavaScript 并显示消息。

于 2009-10-06T17:51:41.057 回答
0

我想这就是你正在尝试的,我尝试了这段代码,它对我有用。

Label1.Text = "Hello world";

Page.ClientScript.RegisterStartupScript(this.GetType(), "click", "alert('Messages');", true);

甚至你可以从这里调用 javascript 函数

Label1.Text = "Hello world"; 
     Page.ClientScript.RegisterStartupScript(this.GetType(), "click", "function();", true);
于 2009-10-07T06:45:03.993 回答