简体   繁体   中英

Connecting ASP.NET client-side scripts to instances

Consider this simplified example:

Server side ASP.NET-code:

TextBox theTextBox = ...
theTextBox.Attributes.Add("onchange", "HandleOnChangeEvent");

Client-side javascript:

var numberOfChanges;

function HandleOnChangeEvent() {
   numberOfChanges++;
   alert(numberOfChanges);
}

Now, this works, ie each time the user changes the value in the textbox, a dialog will popup showing the number of times the value in the textbox has changed since the page was loaded.

But what if there are multiple instances of the texbox on the same page? The numberOfChanges is global, thus it will keep track of the total number of changes on the page, for all textboxes. I want it do be instance-specific, for each individual textbox.

What is the preferred way to solve this? Don't know if it matters, but I should mention that my real scenario is much more complex, with more state variables than just one as in this example.

Thanks! /Fredrik

Take advantage of JavaScript's prototype nature and extend textboxes on an as-used basis, like so:

function HandleOnChangeEvent(e) {

    // `e` contains the DOM element that was clicked
    if( !e.numberOfChanges ) e.numberOfChanges = 0; // dynamically set the property
    e.numberOfChanges++;
    alert( e.numberOfChanges );
}

You need to change your onchange attribute to this:

onchange="HandleOnChangeEvent(this);"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM