jQuery-获取数据属性文本值

时间:2019-06-21 03:27:36

标签: javascript jquery

获取未捕获的错误:语法错误,无法识别的表达式:data-key ['lifetimeStays']

想从data-key =“ lifetimeStays”和data-key =“ lifetimeNights”中获取价值

HTML:

<div data-cookies="profile-cred" data-key="lifetimeStays" class="value cookies-value">1110</div>

<div data-cookies="profile-cred" data-key="lifetimeNights" class="value cookies-value">9000</div>

JS:

$("data-key['lifetimeStays']").text();
$("data-key['lifetimeNights']").text();

2 个答案:

答案 0 :(得分:1)

使用$("[data-key='lifetimeStays']").text();data-keyattribute https://api.jquery.com/attribute-contains-prefix-selector/

console.log($("[data-key='lifetimeStays']").text());
console.log($("[data-key='lifetimeNights']").text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-cookies="profile-cred" data-key="lifetimeStays" class="value cookies-value">1110</div>

<div data-cookies="profile-cred" data-key="lifetimeNights" class="value cookies-value">9000</div>

答案 1 :(得分:0)

您的代码$("data-key['lifetimeStays']")表示您选择具有属性data-key的元素lifetimeStays,即元素<data-key lifetimeStays/>

尝试此操作以选择具有特定值的属性

$('[data-key=lifetimeStays]').text()