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');
    });
});

それは機能しますが、2番目のものに当たると正しく機能しません。

ページに存在するすべてのクラスに対して個別に関数を実行できる必要があります。これは可能ですか?

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)は、ループ内の個々のzoomContainerjQueryオブジェクトを参照します。

コード例のコンテキストでは:

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 に答える