为什么 jQuery $(this).text() 在链接中不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1295597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:08:14  来源:igfitidea点击:

Why doesn't jQuery $(this).text() work inside a link?

jquery

提问by Justin Vincent

Any ideas why this doesn't work?

任何想法为什么这不起作用?

<a href="javascript:alert($(this).text())">Alert This Text Here</a>

I am expecting it to alert "Alert This Text Here", but instead I get a jQuery error (G is undefined)

我期待它提醒“在此处提醒此文本”,但我收到了一个 jQuery 错误(G 未定义)

What am I missing?

我错过了什么?

回答by Sampson

I would assume that "this" has no association to the link you're clicking. It was never given association. thisdoesn't derive its association from markup/syntax.

我认为“这个”与您点击的链接没有关联。它从未被赋予关联。this不从标记/语法派生其关联。

The following works:

以下工作:

<a href="#" onClick="alert($(this).text());">Some Text</a>

Ideally, you want to keep your scripting separate from your markup. You should do it like this:

理想情况下,您希望将脚本与标记分开。你应该这样做:

$("a.someClass").click(function(event){
  event.preventDefault();
  alert($(this).text());
});

This example would require your anchor to have a class="someClass" to function.

这个例子需要你的锚有一个 class="someClass" 来运行。

回答by Sean Clark Hess

<a id="alert">Alert This Text Here</a>
...
$(function() {
  $("#alert").click(function() {
    alert($(this).text());
  });
});

As the above poster mentioned, the this needs to be in a selector to have context.

正如上面的海报提到的, this 需要在选择器中才能有上下文。

回答by spoulson

If you use the "onclick" event handler, thiswill be available to obtain the text().

如果使用“onclick”事件处理程序,this将可获得text().

回答by brendan

In jQuery $(this) refers to a jQuery object usually in the context of a loop or some other selector. So basically you want to select an object in jquery then use the $(this).

在 jQuery 中,$(this) 通常是指循环或其他选择器上下文中的 jQuery 对象。所以基本上你想在jquery中选择一个对象然后使用$(this)。

Example:

例子:

$("a").click(function(){alert($(this).text());});  

This will work because the $(this) is in the context of the selected links.

这将起作用,因为 $(this) 位于所选链接的上下文中。

I think you're getting it confused with the standard javascript "this" reference which will give you the current DOM object.

我认为您将它与标准的 javascript“this”参考混淆了,后者将为您提供当前的 DOM 对象。

This post gives a nice explanation: http://remysharp.com/2007/04/12/jquerys-this-demystified/

这篇文章给出了一个很好的解释:http: //remysharp.com/2007/04/12/jquerys-this-demystified/