开发者

Toggle the icon on a jQuery UI button when clicked

I'm writing a web app for a mobile phone and I want all of the checkboxes to be buttons with either a "check" or "cross" on them, along with the text of the checkbox. I've got a working solution using jQuery UI, but it doesn't seem every elegant. Can anyone suggest any improvements?

Here's the code:

$(function () {
    $("input[type=checkbox]")
    .button({ icons: { primary: "ui-icon-circle-close"} })
    .click(function () {
        if (this.checked) {
            $(this).button("option", "icons", { primary: 'ui-icon-circle-check' })
        }
        else {
            $(this).button("option", "icons", { primary: 'ui-icon-circle-close' })
        }
    });
    $("input[type=checkbox]:checked")
    .button({ icons: { primary: "ui-icon-circle-check"} })
    .click(function () {
        if (this.checked) {
            $(this).button("option", "icons", { primary: 'ui-icon-circle-check开发者_JAVA技巧' })
        }
        else {
            $(this).button("option", "icons", { primary: 'ui-icon-circle-close' })
        }
    });
});


This option ought to be part of jqueryui.

You could simplify with this:

$("input:checkbox")
    .button({
        icons: {primary: "ui-icon-circle-close"}
    })
    .click(function () {
        if (this.checked) {
            $(this).button("option", "icons", {primary: "ui-icon-circle-check"})
        }
        else {
            $(this).button("option", "icons", {primary: "ui-icon-circle-close"})
        }
    })
    .filter(":checked").button({icons: {primary: "ui-icon-circle-check"}});


You can do this more easily using CSS. Just place the following in your style sheet (must be loaded after the jquery-ui.css):

input:checkbox + label .ui-icon {
    background-position: -32px -192px; /* position for ui-icon-circle-close */
}

input:checkbox:checked + label .ui-icon {
    background-position: -208px -192px; /* position for ui-icon-circle-check */
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜