getElementById in separate js file doesn't find ASP.net control

被刻印的时光 ゝ 提交于 2019-12-10 21:42:11

问题


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>

But when I have the same thing in a separate file, even though the function is executed - the value of v remains null.

I tried with a simple div and it did find the div.

Why doesn't it find the ASP.net Button?

EDIT

I even added ClientIDMode="Static" to the Button. No change.


回答1:


<%= Button2.ClientID %> is a server code. You cannot run server code in a separate javascript file.

If you want to access Server Control ID from separate javascript, you need to make the ClientIDMode to either preditable or static.

Here is an example.

The following is a code. It is not a good example, but I hope you get the idea.

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.

ASPX

<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 File

function bought1() {
    var s = 'Button1';
    var v = document.getElementById(s);
    v.click();
}




回答2:


Win is correct, your separate JS file will not be rendered by ASP.net.

However, if you simply put

<script type="text/javascript">
        var s = '<%= Button2.ClientID %>';
</script>

above where you load your external file, you will load the value into a global on the page that will be accessible from any scripts loaded after it. Just make sure to give it a name that wont collide with any libraries you have loaded.




回答3:


You should Change the function like this:

function bought1(clientId)
{
    var s = clientId;
    var v = document.getElementById(s);
    v.click();
}    

and would call it in your page markup:

bought1('<%= Button2.ClientID %>')



回答4:


Alternatively, if you want to avoid the messiness of JS globals and dumping asp.net variables altogether, just wrap your button and use a queryselector (or jquery, etc) to grab it:

asp.net:

<div id="button-container">
        <asp:Button ID="button" runat="server" />
</div>

JS:

<script type="text/javascript">
    function bought1()
    {
        var v = document.querySelector("#button-container input");
        v.click();
    }    
</script>


来源:https://stackoverflow.com/questions/17702953/getelementbyid-in-separate-js-file-doesnt-find-asp-net-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!