javascript - jQuery中通过data属性和部分id获取元素

标签 javascript jquery html jquery-selectors custom-data-attribute

我需要通过data属性和jQuery中的id的一部分来获取元素。 我有以下代码。

<div class="bridgeSelectedDiv" id="bridgeDiv_13234" onclick="SelectBridgeLine(this);" data-bridgeuid="b2a42066-00e2-4b6e-bdef-397468573b75"></div>
<div class="bridgeSelectedDiv" id="bridgeDiv_13432" onclick="SelectBridgeLine(this);" data-bridgeuid="b2a42066-00e2-4b6e-bdef-397468573b75"></div>
<div class="bridgeSelectedDiv" id="bridgeDiv_45646" onclick="SelectBridgeLine(this);" data-bridgeuid="b2a42066-00e2-4b6e-bdef-397468573b75"></div>

function SelectBridgeLine(element) {
 var bridgeuid = $(element).attr("data-bridgeuid");
 var partofSelectedBridgeLine = $('div[id^="bridgeDiv_"]').data("bridgeuid");
 console.log(partofSelectedBridgeLine);
}

但它只返回 1 个元素,而不是全部。 有什么线索吗?谢谢!

最佳答案

来自.data()的文档

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

所以这里发生的事情是它仅获取第一个元素的数据值。您需要使用 .each() 迭代它们以获取匹配选择器中的所有元素:

$('div[id^="bridgeDiv_"]').each(function(){
  console.log($(this).data('bridgeuid'))
});

<强> Demo

关于javascript - jQuery中通过data属性和部分id获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24121082/

相关文章:

javascript - JQuery 在链接前面添加文本

javascript - iOS WebApp 不允许定位服务?

javascript - 关闭 Zurb Foundation 5 元标记

Javascript、 Protractor 和增量计数器

javascript - React hooks 的使用效果

javascript - 检测 Firefox 中链接的点击

jQuery 'POST' 授权

javascript - 在放置位置将可拖动对象放入可放置对象中

html - Flexbox 增长或收缩使 div 稍微移动

javascript - 如何使用 CreateJS 将图像在 Canvas 上居中