开发者

How do i chain these two jquery statements into one?

开发者 https://www.devze.com 2023-02-20 23:51 出处:网络
Ok, I want to chain these statements into one, but i don\'t know how it works yet.. I have lots of input in my html file, and then if i click a link, it will just check that link and make other inpu

Ok, I want to chain these statements into one, but i don't know how it works yet..

I have lots of input in my html file, and then if i click a link, it will just check that link and make other input check boxes uncheck.. Here's my current code for that:

$('.category').click(function() {
   $('input[name=category]').attr('checked', false);
   $(this).parent().find('input').attr('checked', true);
}

I think this might b开发者_开发知识库e slow because the second statement will go to its parent and then find the input then checked it.. It might be possible to combine these into one and make it faster?


Seeing that call to .parent().find() on your chain makes me think that you're actually looking for a sibling? You may get better mileage by using the .siblings() function.

With that in mind, you may want to phrase your code like this:

$('.category').click(function(){
    $('[name="category"]').attr('checked',true);
    $(this).siblings('input:checkbox').attr('checked',true);
});

It's difficult to construct a proper chain for your particular DOM without first seeing the code, but the code above should be OK. Doesn't look heavy at all.


You can add extra filtering into your .find() to only look for checkboxes

$(this).parent().find('input[type="checkbox"]').attr('checked', true);


Make finds just once...

var $category = $('input[name=category]');
var $inputs = $('your_parent_selector');
$('.category').click(function() {
   $category.attr('checked', false);
   $inputs.attr('checked', true);
}
0

精彩评论

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

关注公众号