简体   繁体   English

如何在jQuery中使用数据属性定位?

[英]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. 我想要以下内容:单击图像,获取其数据属性值,然后仅在具有相同数据属性值的li项目上运行脚本的其余部分。 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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