简体   繁体   中英

how to pass $(this) object from one function to another?

I think its very basic Object oriented javaScript related question. But I'm still very confused about it. I would like to pass $(this) object from 1 function to another. So that I can get the href attr of the link clicked.

Here my sample code

HTML

<a href="#testblah" class="test" rel="image">TEST</a>
<a href="#blahtest" class="test" rel="video">TEST</a>

JS

$(document).on("click", ".test", function () {

var $this = $(this);
var rel = $this.attr("rel");

if (rel == "image") {
    e.preventDefault();
    openImage($this);
} else if (rel == "video") {
    openVideo($this);
}
});

function openImage($this) {

var href =  $this.attr("href");
alert(href);
}

Check out the examples in the jQuery documentation page . You'll find that the on method applies to the selected elements, in the case of your code, it's the document object. To get the attribute that you want, jQuery is not necessary to wrap the element. Here's a JSBin example . One more thing, try reemplace == with === to get type checking also. Hope it helps

My question had 1 small syntax error please (check 1st comment on question)

Following is the code I ended up using.

$(document).on("click", ".test", function (e) {

    var anchor = $(this);
    var rel = anchor.attr("rel");

    if (rel == "image") {
        e.preventDefault();
        openImage(anchor);
    } else if (rel == "video") {
        openVideo(anchor);
    }
    });

    function openImage(anchor) {
    var href =  anchor.attr("href");
    alert(href);
    }

Thank you!

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