2013-05-04 65 views
1

我有一些:由wordpress初始化的複選框元素。 現在我設定.buttonset()函數來#format但這不是工作... 這樣的例子:http://jqueryui.com/button/#checkbox無法在jQuery上運行.buttonset()

HTML:

<div id="format"> 
    <?php 
    $categories = get_categories(); 
    foreach ($categories as $category) { ?> 
    <input type="checkbox" name="check" value="<?php echo $category->cat_ID; ?>"> 
    <label><?php echo $category->cat_name;?></label><?php } ?> 
</div> 

JS:

$('#format').buttonset(); 
$('input[type=checkbox]').removeClass('ui-helper-hidden-accessible'); 

$(':checkbox[name=check]').each(function(i){ 
    var nameID = 'check'+ (i+1); 
    this.id = nameID; 
    $(this).next('label').prop('for', nameID); 
}); 
+0

你會得到任何錯誤..檢查你控制檯 – bipen 2013-05-04 17:03:34

+0

是否包裝在'document.ready'中? – charlietfl 2013-05-04 17:07:03

+0

@bipen與螢火蟲沒有錯誤 – pouya 2013-05-04 17:08:59

回答

0

你所有的複選框具有相同的名稱「檢查」。 試着這樣做:

<div id="format"> 
    <?php 
    $i = 0; 
    $categories = get_categories(); 
    foreach ($categories as $category) { ?> 
    <input type="checkbox" name="check<?php echo $i ?>" value="<?php echo $category->cat_ID; ?>"> 
    <label><?php echo $category->cat_name;?></label> 
    <?php 
     $i++; 
     } 
     ?> 
</div> 

然後在您的JS:

$(':checkbox[name^=check]').each(function(i){ 
    var nameID = 'check'+ (i+1); 
    this.id = nameID; 
    $(this).next('label').prop('for', nameID); 
}); 

然後jQuery將發現與名稱檢查開始,爲 「check1」, 「checkblabla」 等所有複選框... 「$('#format')。buttonset();」需要在「換」之後來臨。 字體:

http://api.jquery.com/attribute-starts-with-selector/

編輯:

我覺得你並不真正需要改變與JS,你能做到這一點只用PHP,那麼:

<div id="format"> 
    <?php 
    $i = 0; 
    $categories = get_categories(); 
    foreach ($categories as $category) { ?> 
    <input type="checkbox" name="check<?php echo $i ?>" value="<?php echo $category->cat_ID; ?>"> 
    <label for="check<?php echo $i ?>"><?php echo $category->cat_name;?></label> 
    <?php 
     $i++; 
     } 
     ?> 
</div> 

然後在你的js:

$("#format").buttonset(); 
+0

不,不起作用.... – pouya 2013-05-04 17:17:31

+0

不,不起作用....但現在'

+0

第二種解決方案沒有工作?你能複製我生成的HTML嗎? – Scoup 2013-05-04 17:59:07