How to use JavaScript strings to create a '<%= ...ClientID %>' dynamically?
Hi I trying to write a javascript generate <%= element.ClientID% >
where element is one of the input parameter of function. I am trying to write a variable
var elementName = "<%=" + elemen开发者_开发百科t + ".clientID%>"
which is giving an error
CS0117: 'string' does not contain a definition for 'clientID'
This throws an error because the server-side processing of <% %> tags happens first. Then, the result is output as text, which is JavaScript in this case. So, the server sees this <%=" + element + ".clientID%>
and throws an error because it can't understand that. It's assuming that the string " + element + "
is the value that has .clientID
called on it.
There are two ways that you can get around this.
Option 1: Output All IDs
Make a hash of all possible values of element. If you have more than a couple, this method probably won't work for you.
var elements = [
coolbutton: '<%= coolbutton.ClientId %>',
simplebutton: '<%= simplebutton.ClientId %>',
otherbutton: '<%= otherbutton.ClientId %>'
];
Then you can get the id by doing this:
var elementId = elements[element];
Option 2: Use Ends-with
If you can use jQuery, then there is handy way to refer to ASP.Net controls by ID. Essentially, all ASP.Net Ids end with the actual variable name you use in the code behind. So, if you have an element called CoolButton, you can find it in javascript, using jQuery, like so:
var element = $('[id$=CoolButton]');
The $= operator means ends-with. So, it finds all elements on the page that have an ID that ends with CoolButton. The actual ID of the ASP.Net control on the page will be something long, but it will always end with something like NamingContainer$CoolButton
.
If you can't use jQuery, you could write this logic yourself.
function findByIdEndsWith(endId) {
//loop through all elements on the page
//if the current element's id ends with endId, return it
//return null;
}
This type of function is discussed more here.
As EndangeredMassa points out, your server-side processing is evaluating <% %> (perhaps ERB?).
Try escaping the <%= with <%=
精彩评论