开发者

Writing a new jQuery plugin

<table class="data" border="1">
    <tbody>
        <tr>
        </tr>
            <td><input type="checkbox" /></td>

        <tr>
            <td><input type="checkbox" /></td>

        </tr>
        <tr>
            <td><input type="checkbox" /></td>
        </tr>        
    </tbody>
</table>

While iterating through each tr element, check whether the given <tr> element has a checked checkbox, if so add the new class. If not, remove it.

jQuery.fn.deleteMark = function() {

   this.each(function() {
        alert( $('input:checkbox',this) );
        if ($('checkbox',this).is(':checked')){
            $(this).addClass("delemarked");
        }
        else{
            $(this).removeClass("delemarked");
        }
   })
};

Now I want to add a class to each tr that is checked:

function refresh(){
    $('.data tbody tr').each(function() {
        $(this).deleteMark();
    });        
}

S开发者_高级运维adly this doesn't work for me. I will be grateful for any help.


Instead of checkbox, you need :checkbox for a selector, as there are no <checkbox> elements, like this:

$(':checkbox',this)

Though you can shorten your overall approach with .toggleClass("className", bool), like this:

jQuery.fn.deleteMark = function() {
  return this.each(function() {
    $(this).toggleClass("delemarked", $(this).find(":checkbox:checked").length > 0);
  });
};

Also, there's no need for the .each() calling your plugin, just this will do:

$('.data tbody tr').deleteMark();

You can test all of the change above here.


You example has this: $('checkbox',this)

The reason it isn't working is that you're referencing checkbox as if it were an element name, which it isn't.

Instead, you need to be using [type=checkbox] or just :checkbox (these two do exactly the same thing)

So your code would look like this:

if ($('[type=checkbox]',this).is(':checked'))

or this:

if ($(':checkbox',this).is(':checked'))

See the checkbox selector JQuery manual page for more info.

Hope that helps.


You don't really need a plugin for that:

$('.data tbody tr:has(:checkbox:checked)').addClass("delemarked");
$('.data tbody tr:has(:checkbox:not(:checked))').removeClass("delemarked");

or (depending on your taste)

$('.data tbody tr:has(:checkbox)').removeClass("delemarked").has(':checkbox:checked').addClass('delemarked');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜