简体   繁体   中英

How to select an element efficiently in the same parent div using jQuery

I have a loop that produces many divs in my document that resemble the markup below:

<div class="row">
    <p></p>
    <p></p>
    <div>
        <p>Blah blah blah</p>
        <img src="" />
        <div class="radio">
            <input type="radio" name="myNamedInput">
            <input type="radio" name="myNamedInput">
        </div>
    </div>
    <div class="controls">
        <a href="#">
    <div>
</div>

I wanted to know if there was a better way of accessing the value of the grouped radio input in the div.radio element when someone clicks the link in the div.controls element. This is my jQuery code:

$('.controls').on('click', 'a', function () {
    var val = $(this)
        .closest('.row')
        .find('.radio input:radio[name=myNamedInput]')
        .val();
}

Is this the fastest way or is there a better way as I feel mine is quite long? I appreciate any help and insight.

if the parent div have a id:

$('.controls').on('click', function () {
    var val = $("#"+this.parentElement.id + " .radio").val();
}

maybe be a solution...

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