简体   繁体   中英

Using Data Attribute Object as a Selector in jQuery

I have the following data attribute object:

<div data-vp="{
      id: "vp-485858383",
      customTwo: "test"
}">
</div>

I'm trying to target data-vp with the specific id value in jQuery:

$(['data-vp with id:vp-485858383'].parent().find('.fa.fa-times').show();

I'm doing this so I can show only a specific instance of .fa.fa-times rather than all elements with the .fa.fa-times class.

I know the selector above won't work obviously, but is it possible to target both data-vp along with the specific ID?

You can use the attribute-contains selector for that:

 $(function() { $('[data-vp*="id: vp-485858383"]').css('color', 'red'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-vp='{ id: vp-485858383, customTwo: "test" }'> asdf </div> 

Note that your text must be exactly the same.

Another option is to filter the elements based on the data-vp attribute:

 $(function() { $('[data-vp]').filter(function(i, el) { return $(el).data('vp').id == 'vp-485858383'; }).css('color', 'red'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-vp='{ "id": "vp-485858383", "customTwo": "test" }'> asdf </div> <div data-vp='{ "id": "vp-123", "customTwo": "test" }'> asdf </div> 

For that you must have the content of the data-vp attribute to be a valid json string.

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