简体   繁体   English

在jquery中使用“ this”的正确方法是什么?

[英]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. 我想从具有相同类但不同属性的多个元素中捕获元素的title属性。

This is what I have tried: 这是我尝试过的:

HTML 的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 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: jQuery的:

$(this).attr("title")

Plain vanilla JavaScript: 普通香草JavaScript:

this.title

I'd vote for plain JavaScript so you don't incur the overhead of creating a jQuery object for each tag. 我会投票支持纯JavaScript,这样您就不会为每个标签创建jQuery对象而产生开销。

You used attr() method of jQuery object, but this is not jQuery object. 您使用attr()方法jQuery对象,但是this不是jQuery对象。 Use $(this) instead. 使用$(this)代替。

" $(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." $(this)是表示当前元素是焦点的一种非常流行的构造,可以在事件和选择器函数中使用。这等同于JavaScript的this构造,由jQuery的函数包装以提供对jQuery的访问。”

You should use $(this) . 您应该使用$(this) Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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