简体   繁体   中英

jquery li > checkbox parent

I've been researching in stackoverflow and api.jquery for longer than 1h and I decided to ask because there is something I am missing here and I don't know what is it.

<ul>
    <li>
        <input type="checkbox" **checked**>
        FIRST
    </li>
    <li>
        <input type="checkbox">
        SECOND
    </li>
    <li>
        <input type="checkbox">
        THIRD
    </li>
</ul>

It is more or less, like that. I have let the First input 'checked' by default for the test. I would like to relate the checkbox with its closest li (for future Remove-function). And this is my impossible part. I have tried .parent() .closest .prev() but it all gives me nothing (nothing that I would like). That's my js code, the one I am testing:

if($('input').prop('checked')) {
    $(this).parent('li').css('color','red');
}

The this has nothing to do with the checked input in your code. It is most likely the window object, it does not magically get the context of what you selected above.

Other issue is you are not looking for the checked input, you are selecting all of the inputs and when you read the prop, it is selecting the first input from the list, it is not checking them all for a checked input.

So you need to change your selector, you need to use each and now the this would be the input element that is checked.

$('input:checked').each(function(){
    $(this).parent('li').css('color','red');
});

And this needs to be run on document ready or after the elements are rendered on the page. And there is no need for the each, just showing you the this, you can just chain the calls.

$('input:checked').parent('li').css('color','red');

And please learn about the label element.

First, let's look at your code:

// `.prop` does not select elements,
// it returns a property of an element,
// therefore whether the first <input>
// on the page is checked.
if($('input').prop('checked')) {
    // `this` likely does not refer to anything useful
    // Usually, it's only safe to use `$(this)` in `.each`
    // and event handlers.
    $(this).parent('li').css('color','red');
}

I think you want something like this ( check it out here ):

// Query for all <input>s which are checked
$('input:checked')
// Select their <li> parents
.parent('li')
// Apply CSS (or do whatever you want, e.g. remove())
.css('color','red');

First, if you are trying to check the condition on the document.ready, you'll have to find that input which is already selected, without giving the name parameter, checked will not work properly.

your above code will work after giving some event handlers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM