我需要通过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/