Javascript 带有jQuery ui主题的自动样式复选框

Javascript 带有jQuery ui主题的自动样式复选框,javascript,jquery,jquery-ui,Javascript,Jquery,Jquery Ui,(这里是jquerynoob) 我正在尝试编写一个脚本,当我编写时,它会自动将其转换为jqueryui按钮,看起来像一个复选框。 到目前为止的示例代码 var newCheckboxID = 0; $( "input:checkbox" ).attr('id', "cbx-" + nextCheckboxID++); // how to do that? $( "input:checkbox" ).after("<lab

(这里是jquerynoob)

我正在尝试编写一个脚本,当我编写
时,它会自动将其转换为jqueryui按钮,看起来像一个复选框。 到目前为止的示例代码

var newCheckboxID = 0;
$( "input:checkbox" ).attr('id', "cbx-" + nextCheckboxID++); // how to do that?
$( "input:checkbox" ).after("<label style='width:16px; height:16px; vertical-align:middle;'></label>");
$( "input:checkbox" ).next().attr("for", $(this).attr('id') ); // doesn't work for sure
$( "input:checkbox" ).button();
$( "input:checkbox" ).button( "option", "text", false );
$( "input:checkbox" ).attr("onclick", "$(this).button( 'option', 'icons', {primary:((this.checked)?'ui-icon-check':null),secondary:null} )");
        
var newCheckboxID=0;
$(“输入:复选框”).attr('id',“cbx-”+nextCheckboxID++);//怎么做?
$(“输入:复选框”)。在(“”)之后;
$(“输入:复选框”).next().attr(“for”,$(this.attr('id'));//肯定不行
$(“输入:复选框”).button();
$(“输入:复选框”)。按钮(“选项”,“文本”,false);
$(“输入:复选框”).attr(“onclick”,“this.”按钮('option','icons',{primary:((this.checked)?'ui-icon-check':null),secondary:null});
对不起,如果这太明显了,但我已经在这件事上浪费了一个多小时

编辑 最后用老式的方式完成了(因为没有工作部件)。 任何关于使其更紧凑和“更jQuery”的评论都将被推荐。。。 代码示例

// ---- set ids
var checkboxID = 0;
//$( "input:checkbox" ).attr('id', "cbx-" + nextCheckboxID++); // how to do that?
var cboxes = document.getElementsByTagName('input');           // <-- do this instead
for(var i=0; i<cboxes.length; i++){
    if( cboxes[i].getAttribute('type')!='checkbox' ) continue;
    cboxes[i].setAttribute('id', 'cbx-'+checkboxID++);}

// ---- add labels
$( "input:checkbox" ).after("<label style='width:16px; height:16px; vertical-align:middle;'></label>");
//$( "input:checkbox" ).next().attr("for", $(this).attr('id') ); // doesn't work this
for(var i=0; i<cboxes.length; i++){                              // <-- do this instead
    if( cboxes[i].getAttribute('type')!='checkbox' ) continue;
    cboxes[i].nextSibling.setAttribute('for', cboxes[i].getAttribute('id') );}

// ---- create
$( "input:checkbox" ).button();
$( "input:checkbox" ).button( "option", "text", false );
$( "input:checkbox" ).attr("onclick", "$(this).button( 'option', 'icons', {primary:((this.checked)?'ui-icon-check':null),secondary:null} )");
/----设置ID
var checkboxID=0;
//$(“输入:复选框”).attr('id',“cbx-”+nextCheckboxID++);//怎么做?
var cboxes=document.getElementsByTagName('input');// 工作实例:

在下面,我应该注意到两个主要的变化。我添加了CSS来完成您试图对“代码”中的标签所做的工作(它实际上不属于这些标签)

另外,为了“易于jQuery”的使用,我修改了HTML。然而,我仍然在评论中指出,您可以轻松地将其更改回来

HTML

JavaScript/jQuery

然后我简单地添加了以下CSS:

#CheckBoxes .ui-button .ui-button-text {
    background: #A9A9A9;
    display: inline;
    font-size: 16px;
    left: 19px;
    padding: 0;
    position: relative;
    text-indent: 0;
    top: -4px;
}

这其实不是问题,只花了几分钟,我的大部分时间都花在了“玩”上:p,说到这里,我添加了另一个链接,在这里我展示了jQuery的更多用法,并用计时器“玩”了一圈,享受查看它的乐趣,祝未来的爱好者好运@阿波罗数字顺便说一句,欢迎来到StackOverflow,你会喜欢这里的@SpYk3HH-一段很棒的代码,唯一缺少的是作为插件的代码(这样可以更容易地创建checkbox
$(“输入:checkbox”).checkbox();
或像这样简单的东西),甚至与jqueryUI:集成),谢谢分享!我对你的第一把小提琴做了一点改进,也许有人会觉得有用。我发现当选中这些样式化的复选框时(顺便说一句,非常棒),原始(请参阅:随表单提交)复选框的“选中”值没有改变。这里有一个新的修改:我已经修复了这个脚本,如果在创建过程中已经选中了复选框,那么它就不能正常工作。->
.inp-checkbox+label {
    width:16px; 
    height:16px; 
    vertical-align:middle;
}​
// keep in mind, and i will explain, some of these "moving-parts" or not needed, but are added to show you the "ease" of jquery and help you see the solution

//  This global function is designed simply to allow the creation of new checkboxes as you specified, however, if you won't be making check boxes at end user time, then i suggest simply moving it to within the .each statement found later on.
//  Also, this could easily be written as a jQuery plugin so that you could make a "chainable" one-line call to change checkboxes to this but let's get to the nitty gritty first
function createCheckBox(ele, i) {
    //  First I simply create the new ID here, of course you can do this inline, but this gives us a bottleneck for possible errors
    var newID = "cbx-"+i;
    //  below we use the param "ele" wich will be a jQuery Element object like $("#eleID")
    //  This gives us the "chainability" we want so we don't need to waste time writing more lines to recall our element
    //  You will also notice, the first thing i do is asign the "attribute" ID
    ele.attr({ "id": newID  })
        //  Here we see "chainability at work, by not closing the last line, we can move right on to the next bit of code to apply to our element
        //  In this case, I'm changing a "property", keep in mind this is kinda new to jQuery,
        //  In older versions, you would have used .attr but now jQuery distinguishes between "attributes" and "properties" on elements (note we are using "edge", aka. the latest jQuery version
        .prop({ "type": "checkbox" })
        //  .after allows us to add an element after, but maintain our chainability so that we can continue to work on the input
        // here of course, I create a NEW label and then immidiatly add its "for" attribute to relate to our input ID
        .after($("<label />").attr({ for: newID  }))
        //  I should note, by changing your CSS and/or changing input to <button>, you can ELIMINATE the previous step all together
        // Now that the new label is added, lets set our input to be a button,
        .button({ text: false }) // of course, icon only
        //  finally, let's add that click function and move on!
        //  again, notice jQuery's chainability allows us no need to recall our element
        .click(function(e) {
            //  FYI, there are about a dozen ways to achieve this, but for now, I'll stick with your example as it's not far from correct
            var toConsole = $(this).button("option", {
                icons: {
                    primary: $(this)[0].checked ? "ui-icon-check" : ""
                }
            });
            console.log(toConsole, toConsole[0].checked);
        });
    //  Finally, for sake of consoling this new button creation and showing you how it works, I'll return our ORIGINAL (yet now changed) element
    return ele;
}

$(function() {
    //  This .each call upon the inputs containing the class I asiged them in the html,
    //  Allows an easy way to edit each input and maintain a counter variable
    //  Thus the "i" parameter
    //  You could also use your ORIGINAL HTML, just change $(".inp-checkbox") to $("input:[type='checkbox']") or even $("input:checkbox")
    $(".inp-checkbox").each(function(i) {
        // as previously noted, we asign this function to a variable in order to get the return and console log it for your future vision!
        var newCheckBox = createCheckBox($(this), i);
        console.log(newCheckBox);
    });

    //  This next button added is simply to show how you can add new buttons at end-time
    //  ENJOY!!!
    $("button").button().on("click", function(e) {
        var checkBoxCount = $("#CheckBoxes .inp-checkbox").length;
        var newCheckBox = $("<input />").addClass("inp-checkbox").appendTo($("#CheckBoxes"));
        createCheckBox(newCheckBox , checkBoxCount);
        console.log(newCheckBox);
    });
});​
// First I add a new variable.
// It will simply be for a new "wrapper" element, in which to ensure our button is encased. 
// Giving this element a new class gives easy access for later CSS or Event Triggering of sub elements (like the checkbox)
var newID = "cbx-"+i,
    wrapper = $('<div />', { 'class': 'ui-checkbox-wrapper' }).appendTo('#CheckBoxes');
//  Then I added a line to our ele series of methods.
//  This line simply append our element (checkbox) to our new wrapper
// Take Note at how I added this method at start rather than at end.
// Had I not done this, then the label would not have been wrapped!
ele.appendTo(wrapper)   //  <-- new line!
    .attr({ "id": newID  })
#CheckBoxes .ui-button .ui-button-text {
    background: #A9A9A9;
    display: inline;
    font-size: 16px;
    left: 19px;
    padding: 0;
    position: relative;
    text-indent: 0;
    top: -4px;
}