在JavaScript中使用服务器端代码 [英] Using server side code in JavaScript
问题描述
出于某种原因,我想实现像
< script language = < span class =code-string> javascript type = 文本/ JavaScript的跨度>>
var value =<%TextBox1.Text %> ;
< / script>
但它不起作用,我知道一种方法就是
var value = $(' #<%= TextBox1.ClientID%>')。val();
但我只是想知道为什么第一个总是返回一个空值,任何想法?
(' #<%= TextBox1.ClientID%> 跨度>)VAL();
但我只是想知道为什么第一个总是返回一个空值,任何想法?
请参阅我对解释ASP.NET应用程序如何使用JavaScript的问题的评论。没有使用,服务器端和JavaScript之间的呼叫 - 一个在服务器端,另一个在客户端。
现在,我会解释为什么第一个代码片段不起作用,第二个代码片段起作这只是JavaScript和jQuery。首先,TextBox.Text
在JavaScript文本的实例中被硬编码为当前的一些文本值。它对JavaScript没有任何意义,因为无论价值如何,这都是一些随意的等等。它可能是
var value =
//或某些
var value = blah-blah
是的,就这样,即使没有引号。我希望你现在能看到它。它不仅是JavaScript的乱码,它甚至可能无法编译。 JavaScript异常通常对用户隐藏,因此您可以想象结果。
在第二种情况下,jQuery与 id选择器一起使用。实际上,TextBox1.ClientID
会生成HTML中使用的一些HTMLid
,例如
< pre lang =HTML> < 输入 type = text id = someId ... / >
在第二个示例中,使用实际的id
值就像我上面的例子一样,JavaScript会读取:
var value =
(' #someId')。val( );
这是通过HTML DOM对象获取jQuery包装器的有效方法(
For some reason I want to implement code like
<script language="javascript" type="text/javascript">
var value = <% TextBox1.Text %>;
</script>
but its not working, I know one way to do it is like
var value = $('#<%= TextBox1.ClientID %>').val();
but I just want to know why the first one always return an empty value, any idea?
('#<%= TextBox1.ClientID %>').val();
but I just want to know why the first one always return an empty value, any idea?
Please see my comment to the question explaining how an ASP.NET application works with JavaScript. There is no "using", calls between server-side and JavaScript — one is on the server side, another — on the client side.
Now, I'll explain why first code fragment is not working and the second does. This is just JavaScript and jQuery. First of all,TextBox.Text
gets hard-coded in the instance of JavaScript text as some text value at the moment. It makes no sense for JavaScript, as this is some arbitrary blah-blah, whatever the value is. It could be
var value =
// or some
var value = blah-blah
Yes, just so, even without quotation marks. I hope you can see it now. Not only it is gibberish to JavaScript, it may not even compile. JavaScript exceptions are usually hidden from the user, so you can imagine the result.
In second case, jQuery is used with id selector. Actually,TextBox1.ClientID
generates some HTMLid
used in HTML, like in
<input type=text id="someId" ... />
In your second sample, with the actualid
value like in my example above, the JavaScript will read:
var value =
('#someId').val();
This is a valid way to get a jQuery wrapper over HTML DOM object (
这篇关于在JavaScript中使用服务器端代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!