I can define icon for a jquery ui button in code like this;
$( ".se开发者_StackOverflow中文版lector" ).button({ icons: {primary:'ui-icon-gear'} });
but I would like to define button icon in HTML code. for example
<a href="#" class="jqbutton ui-icon-gear">button</a>
this way I can only call.. $( ".selector" ).button(); in onready event and define icons in code. otherwise I need to call button() method for every button that have different icon.
You could use the Metadata Plugin.
<a href="#" class="jqbutton {icon: ui-icon-gear}">button</a>
And the script
$(".jqbutton")
.each(function(){
var data = $(this).metadata();
$(this).button({ icons: {primary:data.icon} });
});
I've never used this directly, but I have used it through its support in the jquery validation plugin.
The Metadata Plugin works fine, and you can even do more: you can also set ALL the init properties of a jQuery UI button (other widgets too):
<script type="text/javascript">
$(document).ready(function(){
$('.jq-button').each(function(){
var meta=$(this).metadata();
$(this).button(meta);
});
});
</script>
<a href="#" class="jq-button {icons: {primary: 'ui-icon-new'}}">New item</a>
Thanks, TJB - great idea! :)
You can set the icon after initializing the button using the "options"
parameter
$(".jqbutton").button();
$(".jqbutton.ui-icon-gear").button( "option", "icons",
{primary:'ui-icon-gear'} );
http://jqueryui.com/demos/button/#option-icons
EDIT: the link isn't direct, so just look for the Options tab and select 'icons' then look @ the section that says 'Get or set the icons option, after init'
The following code looks for "ui-icon-[icon-name]" in the class-attribute of all elements containing the class "jqbutton" and creates a button with an "ui-icon-[icon-name]" icon.
$(function() {
$(".jqbutton").each(function() {
var obj = $(this);
var icon = false;
var c = obj.attr('class');
var i1 = c.indexOf('ui-icon-');
if (i1 != -1) {
var i2 = c.indexOf(" ", i1);
icon = c.substring(i1, i2 != -1 ? i2 : c.length);
obj.removeClass(icon);
}
obj.button({
icons : {
primary : icon
}
});
});
});
精彩评论