简体   繁体   中英

Multiple element, same class, get value of one element - jquery

I have this multiple elements with the same class.

<div class="test-container">
    <a class="dup-class">
        Get Value
    </a>

    <div class="product-list-col">
        1
    </div>
</div>

<div class="test-container">
    <a class="dup-class">
        Get Value
    </a>

    <div class="product-list-col">
        2
    </div>
</div>

<div class="test-container">
    <a class="dup-class">
        Get Value
    </a>

    <div class="product-list-col">
        3
    </div>
</div>

If I click the the <a> tag on the first div, it should alert the value of .product-list-col value which is 1

if I click the second div of anchor tag, it should alert 2

here's the code for it

$(".dup-class").on('click', function() {
    cont = $(this + " .product-list-col").text();
    alert(cont);
});

Any solution for this stuff?

Here's the jsfiddle of it: http://jsfiddle.net/Vigiliance/PLeDs/3/

You could use siblings(), the reason why your code doesn't work is because it's selecting all .product-list-col

$(".dup-class").on('click', function () {
    cont = $(this).siblings('.product-list-col').text();
    alert(cont);
});

or use .next()

$(".dup-class").on('click', function () {
    cont = $(this).next('.product-list-col').text();
    alert(cont);
});

do this:

$(".dup-class").on('click', function() {
    cont = $(this).next().text(); // this is the line where change done
    alert(cont);
});

http://jsfiddle.net/PLeDs/2/

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