简体   繁体   English

如何使点击捕捉器正常工作?

[英]How do I make my click catcher work?

I'm trying to create a simple click catcher where if you click .image-class the javascript will take the href from another element with a class name of .btn and send you to it's destination. 我正在尝试创建一个简单的点击捕获器,如果您单击.image-class那么javascript将从另一个元素中获取href,该元素的类名为.btn并将其发送到它的目的地。 Though I keep getting errors on lines 7 & 10 saying that undefined is not a function. 尽管我在第7行和第10行上不断收到错误,说undefined不是函数。 How do I make this work? 我该如何工作?

<script>
var ClickCatcher=
{
    init:function(){
        var link = jQuery('.btn')[1].href;
        var imgCatch = jQuery('.image-class');
        imgCatch.addEventListener("click", ClickCatcher.clickListener, false);
    },
    clickListener:function(){
        window.location = link;
    }
};
ClickCatcher.init();
</script>

You can do this with jquery with a simple click event 您可以使用简单的click事件通过jquery执行此操作

jQuery('.image-class').on('click', function (){
    window.location = jQuery('.btn').eq(1).attr('href');
});

But if you still want to write in the way you have you can do: 但是,如果您仍然想以自己的方式编写,则可以执行以下操作:

var ClickCatcher = {
    init: function () {
        jQuery('.image-class').on('click', function (){
            window.location = jQuery('.btn').eq(1).attr('href');
        });
    }
};

ClickCatcher.init();

Just make sure to fire the init method after dom load. 只需确保在dom加载后触发init方法即可。

update: One issue with it is that you have coded your target etc in the code rather then pass it, so its going to be hard to reuse, you'd be better off doing: 更新:这样做的一个问题是,您已经在代码中编码了目标等,然后又将其传递了,因此将很难重用它,您最好这样做:

var ClickCatcher = {
    init: function ($button, loc) {
        $button.on('click', function (){
            window.location = loc;
        });
    }
};

ClickCatcher.init(jQuery('.image-class'), jQuery('.btn').eq(1).attr('href'));

That way the internal working is seperate from the dom (as you are passing the dom dependencies to the function. 这样,内部工作与dom是分开的(因为您将dom依赖项传递给函数。

@atmd showed a very good way of doing this. @atmd显示了一种非常好的方法。 If you just want to know what your mistake was though. 如果您只想知道自己的错误是什么。 It is wa an error in your jQuery stament to get the btn href 获取btn href在jQuery平台中是一个错误

jQuery('.btn')[1].href

you need to call the attr function and then get the href attr. 您需要调用attr函数,然后获取href属性。 and use .eq(1) to reduce the set to the first btn 并使用.eq(1)将集合减少为第一个btn

jQuery('.btn').eq(1).attr('href);

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

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