在的getElementById单独的js文件没有找到ASP.net控制 [英] getElementById in separate js file doesn't find ASP.net control
问题描述
当我有这个页面标记正常工作:
When I have this in the page markup it works fine:
<script type="text/javascript">
function bought1()
{
var s = '<%= Button2.ClientID %>';
var v = document.getElementById(s);
v.click();
}
</script>
但是,当我在一个单独的文件一样的东西,即使函数的是的执行 - 诉code>值保持
空
。
But when I have the same thing in a separate file, even though the function is executed - the value of v
remains null
.
我试着用一个简单的 DIV
,它的没有的找到 DIV
。
I tried with a simple div
and it did find the div
.
为什么它不找到ASP.net按钮?
Why doesn't it find the ASP.net Button?
修改
我甚至增加的ClientIDMode =静态
的按钮。没有变化。
I even added ClientIDMode="Static"
to the Button. No change.
推荐答案
&LT;%= Button2.ClientID%GT;
是一个服务器code。你不能在一个单独的JavaScript文件中运行服务器code。
<%= Button2.ClientID %>
is a server code. You cannot run server code in a separate javascript file.
如果您想从单独的JavaScript访问服务器控件的ID,你需要做的的ClientIDMode
要么preditable或静态的。
If you want to access Server Control ID from separate javascript, you need to make the ClientIDMode
to either preditable or static.
<一个href=\"http://www.west-wind.com/weblog/posts/2010/May/04/Whats-New-in-ASPNET-40-Part-Two-WebForms-and-Visual-Studio-Enhancements\">Here就是一个例子。
以下是code。这不是一个很好的例子,但我希望你的想法。
The following is a code. It is not a good example, but I hope you get the idea.
的注意:确保当您使用您不具有相同的ID 的ClientIDMode =静态
。否则,ID将发生碰撞。例如,一个在主页,一个在内容页。的
Note: Make sure you do not have same Ids when you use ClientIDMode="Static"
. Otherwise, Ids will collide. For example, one in master page and one in content page.
<script src="/JavaScript1.js"></script>
<asp:Button runat="server" ID="Button1" ClientIDMode="Static"
Text="I am a button" />
<div onclick="bought1()">Click Me</div>
JavaScript文件
function bought1() {
var s = 'Button1';
var v = document.getElementById(s);
v.click();
}
这篇关于在的getElementById单独的js文件没有找到ASP.net控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!