[英]jquery get element by attribute and class
如果我有一個元素:
<div>
<div class="foo bar" data-id="12345"></div>
<div class="foo bar" data-id="678"></div>
<div class="foo bar" data-id="910"></div>
</div>
如何獲取具有data-id="12345"
和class="foo bar"
的元素?
謝謝
嘗試這個
$("div.foo.bar[data-id='12345']");
如果要訪問具有class='foo bar'
和data-id=12345
div:
var element = $("div.foo.bar[data-id=12345]");
如果只想訪問第一個具有class ='foo bar'的div元素:
var element = $("div.foo.bar:nth-child(1)");
鏈接類選擇器,然后根據data參數進行過濾:
$(function() {
$("div.foo.bar").filter(function() {
return $(this).data("id") == "12345";
});
});
jsFiddle演示
您還可以輕松地將此邏輯包裝到可重用和可擴展的函數中:
function getDivWithDataId(id) {
return $("div.foo.bar").filter(function() {
return $(this).data("id") == id;
});
}
返回與相關div元素匹配的jQuery集合。
您可以擴展它以包括類(通過傳遞類的數組,例如['foo','bar']
):
function getDivWithDataId(id, classes) {
return $("div").filter(function() {
var $self = $(this);
var classMatch = true;
$.each(classes, function(idx, val) {
if (!$self.is(val)) classMatch = false;
}
return $(this).data("id") == id && classMatch;
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.