簡體   English   中英

在jQuery中使用數據屬性對象作為選擇器

[英]Using Data Attribute Object as a Selector in jQuery

我有以下數據屬性對象:

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

我正在嘗試使用jQuery中的特定id值來定位data-vp:

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

我這樣做是為了僅顯示.fa.fa-times的特定實例,而不顯示.fa.fa-times類的所有元素。

我知道上面的選擇器顯然不能正常工作,但是可以同時將data-vp和特定的ID作為目標嗎?

您可以為此使用attribute-contains選擇器:

 $(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> 

請注意,您的文字必須完全相同。

另一個選擇是根據data-vp屬性過濾元素:

 $(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> 

為此,您必須將data-vp屬性的內容設置為有效的json字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM