我制作了以下代码来转换必须应用 jquery.ui 样式的所有a
元素、input type="submit
元素、button
元素和手风琴div。
我使用了 prop('type') 和 tagNames 来找出我正在迭代的控件:
$(function () {
$('body *:not(script, style, noscript)').each(function () {
var t = $(this).prop('type');
if (t != undefined && t !="") {
if (t.indexOf("select") != "-1") {
$(this).combobox();
}
else if (t.indexOf("button") != "-1") {
$(this).button();
}
}
if ($(this).get(0).tagName == "DIV" &&
$(this).get(0).id != undefined &&
$(this).get(0).id.toUpperCase() == "ACCORDION") {
$(this).accordion({ collapsible: true });
} else if ($(this).get(0).tagName == "A" ||
($(this).get(0).tagName == "INPUT" &&
$(this).prop('type') == "submit")) {
$(this).button();
}
});
});
显然,这工作很棒。这个 jquery ready 函数包含在我的 asp.net mvc 布局页面中,当我添加新控件时,它会呈现 jquery-ui。
但问题是。你有没有做过这样的事情?有没有更好的方法?
你可以利用jQuery来简化你的代码:
$(function() {
// Use selectors to get DOM elements you are interested in
$('a, input[type=submit], button, select, .accordion').each(function() {
// Create the jQuery object only once, avoid doing $(this) each time
var $el = $(this);
if($el.is('a') || $el.is('input[type=submit]') || $el.is('button'))
$el.button();
else if($el.is('.accordion'))
$el.accordion({ collapsible: true });
else if($el.is('select'))
$el.combobox();
});
});
但更简单/可读的方法可能是这样的:
$(function() {
$('a, input[type=submit], button').button();
$('.accordion').accordion({ collapsible: true });
$('select').combobox();
});
在这个jsFiddle中看到它的实际效果
注意 1:我用 css 类accordion
(选择器 .accordion
)替换了您的测试检查div
是否有 id accordion
。元素 id 在 DOM 树中必须是唯一的,所以如果你有多个 id accordion
的div,请用 css 类accordion
替换它们。
注意2:jQuery UI没有开箱即用的组合框小部件(AFAIK),也许你正在使用 http://jqueryui.com/autocomplete/#combobox