如何使用jquery javascript根据div中的文本查找对应数据attr的值

ntjbwcob  于 2021-09-13  发布在  Java
关注(0)|答案(3)|浏览(265)

我有一些div,它们有一个名称和不同的data attr值 data-category 现在我需要的是 data-category 基于div中的特定文本。

<div class='ext-category' data-category="swimpool">Jack</div>
<div class='ext-category' data-category="swimpool">John</div>
<div class='ext-category' data-category="office">Jennifer</div>
<div class='ext-category' data-category="office">Sue</div>

在js函数中,我可以获取div中的名称:

eventReceive: function(info) {
    var name = info.event['name']; // shows me "Jennifer"

}

我怎样才能抓住它的价值呢 data-category 哪个属于詹妮弗?
我试过:

var category = $(".ext-category").find(name).attr('data-category');
alert(category); // result: undefined (should be office)
b4qexyjb

b4qexyjb1#

下面是一个使用:contains()的快捷方法

const getCategoryFromName = (name) => $(`.ext-category:contains(${name})`).data('category')
console.log(getCategoryFromName('Jennifer'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='ext-category' data-category="swimpool">Jack</div>
<div class='ext-category' data-category="swimpool">John</div>
<div class='ext-category' data-category="office">Jennifer</div>
<div class='ext-category' data-category="office">Sue</div>
l5tcr1uw

l5tcr1uw2#

你可以用 querySelectorAll 循环遍历数据,然后检查哪个元素具有正确的名称,并返回它的数据类别值,如下所示

function findByName(name) {
  const elements = document.querySelectorAll(".ext-category");
  for (let i = 0; i < elements.length; i++) {
    if (elements[i].innerText == name) return elements[i].dataset.category; // Credits to vanowm for suggesting .dataset.category rather than .getAttribute
  }
}

console.log(findByName("Jack"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='ext-category' data-category="swimpool">Jack</div>
<div class='ext-category' data-category="swimpool">John</div>
<div class='ext-category' data-category="office">Jennifer</div>
<div class='ext-category' data-category="office">Sue</div>
nukf8bse

nukf8bse3#

使用 contains 选择器:

var category = $(".ext-category:contains('Jennifer')").attr('data-category');
alert(category);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='ext-category' data-category="swimpool">Jack</div>
<div class='ext-category' data-category="swimpool">John</div>
<div class='ext-category' data-category="office">Jennifer</div>
<div class='ext-category' data-category="office">Sue</div>

相关问题