最近一直在开发Asp.Net MVC项目, 对DNN稍有松懈, 不过由于所有技术都有相通和借鉴之处, 故在学习MVC框架的同时也对DNN有了更深的认识, 由于MVC模式对UI和前端界面的交互有更多的掌握, 需要你更多控制界面上的HTML元素, 包括布局控制和如何呈现等等. 在此想分享一点JQuery在MVC模式下(当然你在其他项目也是可以用到的, 比如DNN或传统的Asp.Net form)如何操作HTML SELECT元素, 其中包括:
1) 清空SELECT所有Options项
2) 动态加载键值对的数据
3) 根据value或text设置选中的Option
等等
/*
* Manipulation for HTML SELECT with jQuery
* Created by Baldwin (http://www.dnnsun.com)
* version: 1.0 (02/03/2009)
* @requires jQuery v1.2 or later
*/
;(function($) {
/* Clear all options */
$.fn.clearSelect = function() {
return this.each(function() {
if (this.tagName == 'SELECT') this.options.length = 0;
});
}
/* Fill the options with the object array: [{'Text':'Hello','Value':'1'}]*/
$.fn.fillSelect = function(data) {
return this.clearSelect().each(function() {
if (this.tagName == 'SELECT') {
var dropdownList = this;
if(data && data.length>0){
$.each(data, function(index, optionData) {
var option = new Option(optionData.Text, optionData.Value);
if ($.browser.msie)
dropdownList.add(option);
else
dropdownList.add(option, null);
});
dropdownList.disabled = false;
}
else
dropdownList.disabled = true;
}
});
}
/* loading when applying Ajax fillSelect */
$.fn.loadSelect = function(loadText) {
var data = [{'Text':loadText,'Value':''}];
this.fillSelect(data);
}
/* selected the target option with value */
$.fn.selected = function(value) {
return this.each(function() {
if (this.tagName == 'SELECT'){
var options = this.options;
if(options.length>0){
$.each(options, function(index, optionData) {
// once match then exist loop
if ( optionData.value==value) {
optionData.selected = true;
return false;
}
});
}
}
});
}
/* TODO:selected the target option with text */
$.fn.selectedText = function(text) {
return this.each(function() {
if (this.tagName == 'SELECT'){
var options = this.options;
if(options.length>0){
$.each(options, function(index, optionData) {
// once match then exist loop
if (optionData.text==text) {
optionData.selected = true;
return false;
}
});
}
}
});
}
/* returns the selected value */
$.fn.getSelected = function() {
return $(this).val();
}
/* return the text of selected option */
$.fn.getSelectedText = function() {
return $(this).children("[@selected]").text();
}
})(jQuery);
:) Enjoy JQuery & DNN!