Javascript Object orientation + DOM?
Im using multiple ASCX controls on one page, and the javascript clashes obviously if I use two of the same control. So Ive changed it all to proper OOP javascript so they dont interfere开发者_开发知识库, but my problem now is how do I do the HTML side of things. Both ASCX's will make a div called "foo". So whats the usual way around this? Am I meant to also be generating all the html from inside my JS classes?
Thanks :)
You can add runat="server"
to your DIVs to make them server-side controls:
<div id="foo" runat="server"> ... </div>
then use the control's (generated) ClientID:
<script>
var divId = "<%= foo.ClientID %>";
</script>
Put them into their own ''containers'': divs with unique IDs such as:
...
<div id="control1">
...
<!-- Control One goes here -->
<div class="foo">...</div>
...
</div>
...
<div id="control2">
...
<!-- Control Two goes here -->
<div class="foo">...</div>
...
</div>
...
You can then manipulate them by first navigating to the uniquely named DIVs, then searching for elements with class foo
.
To access these in Javascript you could use something like:
var c1 = document.getElementById("control1").getElementsByClassName('foo')[0];
var c2 = document.getElementById("control2").getElementsByClassName('foo')[0];
Make sure to use the [0]
on each, because getElementsByClassName
returns an array of elements. You (probably) need only one element (not an array object).
精彩评论