简体   繁体   English

jQuery 数据属性数组选择器

[英]jQuery selector for data attribute array

Theres' this html code:有这个 html 代码:

<div class="wcpa_form_outer" data-attrrelated="[&quot;wcpa-select-1658734650073&quot;]">

for which i'm trying to append html to it.为此,我正在尝试 append html。 I have tried various approaches but none have worked.我尝试了各种方法,但都没有奏效。

jQuery('.wcpa_form_outer[data-attrrelated="[&quot;wcpa-select-1658734650073&quot;]"]').append('some html here');

or或者

jQuery('.wcpa_form_outer[data-attrrelated="[wcpa-select-1658734650073]"]').append('some html here');

or或者

jQuery('.wcpa_form_outer').data('attrrelated').append('some html here');

any clues?任何线索?

The &quot; &quot; and/or [] in the attribute value may be the problem Remove it, or try using a part (the most relevant part?) of the attribute value:和/或属性值中的[]可能是问题删除它,或尝试使用属性值的一部分(最相关的部分?):

 $('[data-attrrelated*="1658734650073"]').append('some html here;'). $('[data-attrrelated*="wcpa-select-165873465007"');append('<br>some html here too!');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wcpa_form_outer" data-attrrelated="[&quot;wcpa-select-1658734650073&quot;]"></div>

Problem is that you're using the HTML Entity &quot;问题是您正在使用 HTML 实体&quot; in your attribute.在你的属性中。 This is being translated to a literal quote.这被翻译成字面引述。 JQuery does not do Entity translation, so it's literally looking for the string [&quot;wcpa-select-1658734650073&quot;] with ampersands and all, not ["wcpa-select-1658734650073"] which is the actual value in your attribute. JQuery 不进行实体翻译,因此它实际上是在寻找字符串[&quot;wcpa-select-1658734650073&quot;]和符号,而不是["wcpa-select-1658734650073"] ,这是您属性中的实际值。

You can work around this by using one of the following methods (after also translating the Entity into a quote in your code).您可以使用以下方法之一解决此问题(在将实体转换为代码中的引号之后)。

  1. Use a CSS "contains" selector for your attribute ( attr*=value ) (demonstrated by KooiInc's answer) or为您的属性( attr*=value )使用 CSS “包含”选择器(由 KooiInc 的回答证明)或
  2. Use a string template which will allow you to embed both types of quotes in your string and get an exact match ( attr=value ), shown below使用一个字符串模板,它允许您在字符串中嵌入两种类型的引号并获得完全匹配 ( attr=value ),如下所示
  3. Constructing a string value containing quotes by using string concatenation (eg '["' + value + '"]' )使用字符串连接构造包含引号的字符串值(例如'["' + value + '"]'
  4. Use the decodeEntities function from this answer to translate your attribute value before attempting the lookup (untested, and it's 10 years old)使用此答案中的decodeEntities function 在尝试查找之前转换您的属性值(未经测试,已有 10 年历史)

 jQuery(`.wcpa_form_outer[data-attrrelated='["wcpa-select-1658734650073"]']`).append('foo')
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wcpa_form_outer" data-attrrelated="[&quot;wcpa-select-1658734650073&quot;]">append here: </div>

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

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