简体   繁体   中英

How to target with data attribute in jQuery?

I created a portfolio in which I have a list item for each image element. I want the following: click on an image, get its data attribute value and run the rest of the script only on that li item which has the same data attribute value. Somewhat like this:

var data1 = $("#portfolio li").data('descriptionid');
var data2 = $('.img-description').data('description');
$('#portfolio li').click(function(){
    $(".img-description").data("img").stop()
    .animate({
        "left" : '0px'
    }, 400);
});

<div id="portfolio">
    <ul>
    <li><img src="img1.jpg" width="320px" data-descriptionid="img1"></li>
    <li><img src="img2.jpg" width="320px"></li>
    </ul>
    </div>
    <div id="idc">
        <ul>
        <li class="img-description" data-description="img1">
            <p>
            Lorem ipsum dolor sit amet, consectetur
            </p>
            </li>
        </ul>
        </div>
</div>

I have a feeling that the variables shouldn't be outside, that i need to store the data in the variable in the moment when I clicked on the specific item. How do I proceed further? Thank you for your help.

At its simplest, I'd suggest:

$('#portfolio li').click(function(){
    $('.img-description[data="' + $(this).data('descriptionid') + '"]').stop()
    .animate({
        "left" : '0px'
    }, 400);
});

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