简体   繁体   中英

Get the index value of the clicked tag in jquery plugin

I've made a plugin for jQuery, I need only click on the tag index have been.

My HTML code:

<body>
    <a href="../img/ib1.jpg" rel="group"class="asd">
        <img src="../img/is1.jpg"/>
    </a>
    <a href="../img/ib2.jpg" rel="group"class="asd">
        <img src="../img/is2.jpg"/>
    </a>
    <a href="../img/ib3.jpg" rel="group"class="asd">
        <img src="../img/is3.jpg"/>
    </a>
    <a href="../img/ib4.jpg" rel="group"class="asd">
        <img src="../img/is4.jpg"/>
    </a>    
</body>

My Plugin Code:

(function( $ ) {
    $.fn.nss = function( ) {
        var elems = this
        return elems.each(function() {
            var thisindx = elems.index(this);
            console.log(thisindx);
        });
    };
}( jQuery ))

this console.log(thisindx) print 0,1,2,3

But I have only clicked tag index value, not the value of all tags

my javascript code:

(function(){
    $('a[rel="group"]').click(function(){
        $('a[rel="group"]').nss();
    })
});

If you really want to build a plugin you should encapsulate your click event inside the plugin:

(function( $ ) {
    $.fn.nss = function( ) {
        var elems = this;
        return elems.on('click', function(e) {
            e.preventDefault();
            var thisindx = elems.index(this);
            console.log(thisindx);
        });
    };
}( jQuery ))

and than just bind it on your elements:

$(function(){
    $('a[rel="group"]').nss();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM