jQuery通过$(this)遍历HTML

jQuery traversing HTML through $(this)

本文关键字:遍历 HTML this 通过 jQuery      更新时间:2023-09-26

我有一个HTML文档,其结构如下:

<section id="page1" data-role="page"> 
    <a href="#" id="next-section" class="next-section" style=" cursor:e-resize"><div class="arearight" alt="go right" ></div></a>
    <a href="#" id="prev-section" class="prev-section" style=" cursor:w-resize"><div class="arealeft" alt="go left" ></div></a>
...   
</section>
<!-- more sections -->

我有下面的代码来遍历它

$(":jqmData(role='page')").each(function() {
    $(this).bind("swipeleft" goLeft); //goLeft and goRight are defined and working
    $(this).bind("swipeleft", goRight);
    //...
}

滑动工作正常,但我想通过click行为绑定到next-sectionprev-section,以调用goLeftgoRight,但我不知道如何通过$(this)对象访问它们。有人知道怎么找到他们吗?

感谢

为它们使用不同的选择器:

$(this).find("#prev-section").click(goLeft);
$(this).find("#next-section").click(goRight);

请注意,您将有多个具有相同ID的元素(#prev部分,#next部分),但ID在整个DOM上应该是唯一的。将其替换为类或数据短划线属性(如用于role=page的属性)。

$('#next-section').bind('click', goRight);
$('#prev-section').bind('click', goLeft);

$('a.next-section').bind('click', goRight);
$('a.prev-section').bind('click', goLeft);

$(this).children('#next-section').bind("swipeleft" goLeft);
$(this).children('#prev-section').bind("swipeleft", goRight);

$(this).find('#next-section').bind("swipeleft" goLeft);
$(this).find('#prev-section').bind("swipeleft", goRight);