jQuery 类选择器和单击事件,我错过了什么吗?

发布于 2024-12-17 20:14:37 字数 790 浏览 0 评论 0原文

我对 jQuery 及其选择器还很陌生。

我有很多用于切换语言的链接。语言存储在languages变量中,当前语言索引(称为lang)存储在document中。当我单击一个链接时,它会正确更改(在数组中循环),但任何其他链接保持不变。为什么? $('.lang') 选择器应该选择我的所有链接...

var languages = ['en', 'sl', 'at', 'de'];
$(document).data('lang', 0); // Just for the first page load

$('.lang').text(languages[($(document).data('lang'))])
    .attr('href', 'javascript:void(0)'); // Set href and text

$('.lang').click(function() {
    // Set link text to the current language and increment counter
    $(this).text(languages[(($(document).data('lang') + 1) % languages.length)]);
    $(document).data('lang', $(document).data('lang') + 1)
});

<a class="lang"></a>
<a class="lang"></a>

I'm quite new to jQuery and its selectors.

I've many links used to switch language. Languages are stored in languages variable, and the current language index (called lang) is stored in document. When i click on one single link it changes correctly (cycle through the array), but any other links remain unchanged. Why? $('.lang') selector is supposed to select all my links...

var languages = ['en', 'sl', 'at', 'de'];
$(document).data('lang', 0); // Just for the first page load

$('.lang').text(languages[($(document).data('lang'))])
    .attr('href', 'javascript:void(0)'); // Set href and text

$('.lang').click(function() {
    // Set link text to the current language and increment counter
    $(this).text(languages[(($(document).data('lang') + 1) % languages.length)]);
    $(document).data('lang', $(document).data('lang') + 1)
});

<a class="lang"></a>
<a class="lang"></a>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

水溶 2024-12-24 20:14:37

这是因为在您的点击函数中,您引用了 this,即您只需要当前已单击的链接,

$('.lang').click(function() {
    // Set link text to the current language and increment counter
    $('.lang').text(languages[(($(document).data('lang') + 1) % languages.length)]);
    $(document).data('lang', $(document).data('lang') + 1)
});

如本 jsfiddle

http://jsfiddle.net/WhtqR/

您是正确的,$('.lang') 将选择该类的所有链接。在您的代码中,它将单击函数应用于每个链接处理程序。但是点击时执行的函数需要该标签而不是 this

It's because in your click function you referring to this, ie only the current link that has been clicked you need

$('.lang').click(function() {
    // Set link text to the current language and increment counter
    $('.lang').text(languages[(($(document).data('lang') + 1) % languages.length)]);
    $(document).data('lang', $(document).data('lang') + 1)
});

as shown in this jsfiddle

http://jsfiddle.net/WhtqR/

You are correct in that $('.lang') will select all of your links with that class. In your code it applies the click function to each of the links handlers. But the function that gets executed on click needed that tag rather than this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文