我有内在的喜欢
$('a[id^="Page"]').each(function () {
if ($(this).attr("id") == pageId) {
$('[id="' + pageId + '"]"').each(function () {
// code here
});
}
});
如何访问当前元素,因为它来自以前的each
this
?
谢谢!
您可以使用回调的第二个参数来获取元素,如下所示:
$('a[id^="Page"]').each(function (index, element) {
if ($(element).attr("id") == pageId) {
$('[id="' + pageId + '"]"').each(function (j, pageElment) {
console.log(element);
console.log(pageElment);
});
}
});
首先,您可以使用以下回调签名来消除this
的使用:
.each(function(outerIndex, outerElement) {
.each(function(innerIndex, innerElement) {
// Do stuff with outerElement...
});
});
这比使用this
重言式更具可读性。
但是,在您的示例中,根本不需要在第一个each(...
中使用第二个each(...
,因为您要查找确切的 id。如果你提前知道pageId
- 你不需要任何each(...
.相反,只需使用 id 选择器:
$('#' + pageId).// Do your stuff
默认情况下
this
是指调用函数的上下文。当您对一个或多个元素调用.each
时,函数内部this
将始终引用当前元素。
只需将this
保存到变量中,然后就可以使用它:
$('a[id^="Page"]').each(function () {
var $that = $(this);
if ($that.attr("id") == pageId) {
$('[id="' + pageId + '"]"').each(function () {
console.log($that.data('val') === $(this).data('val'));
});
}
});
如果您有身份证件作为号码(例如 id="12345"
),而不是阅读此内容