0

有没有办法检查某个元素的任何父母是否是标签?目前,它只检查直接父级,但我想知道是否有办法检查它是否包含在任何 ankor 标签中?

HTML:

<!DOCTYPE html>
<html>
    <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

    </head>
    <body>
        <a class="website">Load Content</a>
        <a href=""><img width="200" height="200" class="zoom" /></a>
        <a href=""><div><img width="78" height="101" class="zoom" /></div></a>
    </body>
</html>

CSS:

.zoomBox {
    position:absolute;  
    opacity:0;
    background: url('http://www.shannonhochkins.com/_images/505706e8965f59080b0016a1') no-repeat center center;    
}

JavaScript:

zoom = function() {    
zoomBoxClass = 'zoomBox';
zoomContainer = $('.zoom');
zoomContainer.each(function() {
    if ($(this).parent().is("a")) {
        var $el = $('<div class="' + zoomBoxClass + '"></div>').insertBefore($(this)),
            zwid = $(this).width(),
            zhei = $(this).height(),
            zpx = $(this).position().left,
            zpy = $(this).position().top;
        $el.css({
            width: zwid,
            height: zhei,
            top: zpy,
            left: zpx
        });;
    };
});

$(document).ready(function() {
    zoom();
    $("." + zoomBoxClass).mouseover(function() {
        $(this).stop(true, true).animate({
            opacity: 1.0
        }, 'slow');
    });
    $("." + zoomBoxClass).mouseleave(function() {
        $(this).stop(true, true).animate({
            opacity: 0
        }, 'slow');
    });
});

它确实有效,但当它击中第二个时不正确。

我需要能够为页面上存在的每个类单独运行该函数。这可能吗?

4

1 回答 1

0

你需要使用一个.each()

zoomContainer.each(function() {
    var zoomBox = $('<div class="zoomBox"></div>').insertBefore($(this));
    // anything else you want to do to zoomBox
});

zoomContainer 是 jQuery 对象的集合,.each()将遍历每个对象,上下文 (this) 指的是循环中的各个 zoomContainer jQuery 对象。

在您的代码示例的上下文中:

zoom = function() {
    zoomBoxClass = 'zoomBox';
    zoomContainer = $('.zoom');

    zoomContainer.each(function () {
        var $el = $('<div class="' + zoomBoxClass + '"></div>').insertBefore($(this)),
            zwid = $(this).width(),
            zhei = $(this).height(),
            zpx = $(this).position().left,
            zpy = $(this).position().top;

        $el.css({
            width: zwid,
            height: zhei,
            top: zpy,
            left: zpx
        });
    });
};

如果您想遍历 DOM 树,直到到达特定标签(如果存在),您可以使用 jquery.closest(selector)

`$(this).closest('a');`

如果要检查是否.closest()返回任何内容,可以检查其长度属性是否 > 0

var $a = $(this).closest('a');

if ($a.length > 0) {
    // do stuff with $a here
}
于 2012-09-19T18:37:47.097 回答