I have an asp.net page w开发者_如何学运维ith several list boxes.
I would like to include some javascript on the page that allows a user to drag individual list elements from one box to another.
On a normal web page, the script to do this is reasonably simple, however, with the element IDs generated by ASP.NET, I don't know what identifiers to have my script look up?
Any thoughts on how to do something like this?
Add a identifying CSS class to your elements and use those. i.e. jQuery has a superb support for that so you can grab all elements and loop through them to do whatever you want.
Check out the ClientId
property of the Control
class.
Note: The ASP.NET ListBox
control inherits from Control
.
Update
In reponse to the comments below, I can think of two ways to access the individual li
elements of an unordered / ordered list generated by the ListBox
control.
- Create a custom
Control
that inherits from theListBox
control and renders out an id attribute for eachli
element. - Use the
getElementsByTagName
method in JavaScript. MSDN even has an example that uses thegetElementsByTagName
method to get the children of an unordered list and displays an alert indicating the number of children and the value of the first child element. If the MSDN documentation isn't your thing, you can check out the MDC documentation as well.
You could either use the ClientId property as stated by paper1337
var element = document.getElementById('<%= MyDropDownList.ClientID %>');
or you could implement a AJAX Behavior using AjaxControlToolkit.
Code:
[assembly: WebResource("MyJS.js", "text/javascript")]
[ClientScriptResource("MyBehavior", "MyJS.js")]
public sealed class MyExtender : BehaviorBase {
// can be empty
}
Markup:
<asp:DropDownList runat="server" ID="DDL" />
<my:MyExtender runat="server" TargetControl="DDL" />
MyJS.js (See AjaxControlToolkit samples for details):
...
var element = this.get_element();
...
If you are on asp.net 4.0+, you can use the ClientIDMode="Static"
to force asp.net to use the id you have specified. There's a nice explanation on ScottGu's blog, and the MSDN Docs for ClientIDMode are available.
You may also want to try ClientIdMode="Predictable"
, if you have a lot of generated elements.
精彩评论