"); T...">

Capturing asp.net controls in javascript

I have a page where it overflows with code like:

var textBox = $get("<%=textState.ClientID%>");

This requires that I have my JavaScript inside the page, and not beautifully threaded into a js file. Is there a better approach to this?

document.getElementById does not work, because then I get code like this:

var textBox = document.getElementById("originDestinationControl_textState");

or

var textBox = document.getElementById("ctl00_ContentPlaceHolder_originDestinationControl_textState");

depending on where I link to these controls (inside the main pages and / or user controls)

+3
source share
4 answers

I usually use something like this on pages where I want to use a separate js file.

<script type="text/javascript">
    var pageNameElements = {
        textbox : '<%= textbox.ClientId %>',
        button : '<%= button.ClientId %>'
    };
</script>

, javascript- , js, .

$('#' + pageNameElements.textbox)

document.getElementById(pageNameElements.textbox)

jquery.

+3

jQuery? , asp, .

var textBox = $get("<%=textState.ClientID%>");

:

var textBox = $("input[id$='_textState']");

jQuery. , js!

+2

, .

Your textState.ClientId code should remain on the aspx page itself. This is due to the fact that it is displayed on the client side. JavaScript-enabled files are uploaded separately from the rest of the page, so he doesn't know how to handle this.

If you need to clear this, you can try using classic asp style files. However, in asp.net they end up adding more clutter than they fix.

0
source

Source: https://habr.com/ru/post/1732391/


All Articles