简体   繁体   中英

What is the correct way to use “this” in jquery?

I want to catch the title attribute of a element from multiple elements having the same class, but different attributes.

This is what I have tried:

HTML

    <div title="title1" class="pager" onclick="location.href='link.aspx';></div>
    <div title="title2" class="pager" onclick="location.href='link.aspx';></div>
    <div title="title3" class="pager" onclick="location.href='link.aspx';></div>
    <a class="pagerTitle"></a>

jQuery

$(".pager").bind("mouseover", function() {
        $(".pagerTitle").text(this.attr("title"));
    });

But it is not working. What is the correct method to do so?

You can use one of two methods:

jQuery:

$(this).attr("title")

Plain vanilla JavaScript:

this.title

I'd vote for plain JavaScript so you don't incur the overhead of creating a jQuery object for each tag.

You used attr() method of jQuery object, but this is not jQuery object. Use $(this) instead.

" $(this) is one of very popular construct to indicate current element is focus, which can be used inside event and selector functions. This is as equal to JavaScript's this construct wrapped by jQuery's function to provide access to jQuery's function."

You should use $(this) . Hope it helps!

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