简体   繁体   English

将点击侦听器添加到JQuery对象数组

[英]Adding click listener to an array of JQuery objects

Here is my javascript: 这是我的JavaScript:

function scrollTo(position) {
    $('body').animate({
        scrollTop: position
    }, 500);
}

var titles = $('.title');
for(var i = 0; i < titles.length; i++) {
    titles[i].click(function() {
        console.log('click');
        scrollTo(0);
    });
}

It's supposed to select all three titles and apply a click listener that will scroll the page back to the top. 应该选择所有三个标题并应用单击侦听器,该侦听器会将页面滚动回到顶部。 Unfortunately I am not getting the message in the console nor is it scrolling. 不幸的是,我没有在控制台中收到消息,也没有滚动消息。

Everywhere I have looked online has given for loops exactly like this to apply a click listener to multiple JQuery objects but for some reason it won't work for me. 我在网上看到的所有地方都给出了完全像这样的循环,以将单击侦听器应用于多个JQuery对象,但是由于某些原因,它对我不起作用。 I'm afraid I may have made a stupid mistake but I can't find it. 恐怕我可能犯了一个愚蠢的错误,但我找不到。

The reason your code did not work was because of this line 您的代码不起作用的原因是因为这一行

titles[i].click(function() {

When you access a jQuery object with a index, you are technically accessing the DOM element and not the jQuery object anymore. 当您访问带有索引的jQuery对象时,从技术上来说,您是在访问DOM元素,而不是jQuery对象。 And the DOM object does not have a click method. 而且DOM对象没有click方法。 If you would have opened your console, you would have seen an error. 如果您打开控制台,将看到错误。 If you still want to use a for loop, you will have to convert that to a jQuery object first. 如果仍然要使用for循环,则必须先将其转换为jQuery对象。

$(titles[i]).click(function() {

If you would have done that, it would work as expected. 如果您这样做,它将按预期工作。

Also if you still do not want to double wrap it, you could have also used .eq to get the jQuery object from the array. 另外,如果您仍然不想对其进行两次包装,则还可以使用.eq从数组中获取jQuery对象。

titles.eq(i).click(function() {

You need not iterate over the jQuery objects to assign event handlers. 您无需遍历jQuery对象即可分配事件处理程序。 You could just do it in one line. 您只需要一行即可完成。

$('.title').click(function() {
    console.log('click');
    scrollTo(0);
 });

Also check the version of jQuery you are using, if it is the latest then you could use on 还要检查您使用的jQuery版本,如果它是最新版本,则可以on

$('.title').on('click', function() {

Also you need to make sure that the elements with class title are present on the page when you associate the events. 关联事件时,还需要确保页面上存在带有类title的元素。

you can use this, should give you what your looking for. 您可以使用它,应该给您您想要的东西。

$('.title').click(function () {
   $('body,html').animate({
        scrollTop: 0
    }, 600);
    return false;
});

also as Sushanth said, if you have a new version of jQuery you can use .on(click) 也如Sushanth所说,如果您有新版本的jQuery,则可以使用.on(click)

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

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