简体   繁体   English

将元素存储到对象中以用作点击处理程序无法正常工作(jQuery / javascript)

[英]Storing an element into an object to use as a click handler doesn't work correctly (jQuery/javascript)

This code works correctly: 这段代码可以正常工作:

function clickHandler(){
    $(config.container).find('.'+config.play).on('click',function(){
        console.log('clicked');
    }
}

However when I place the element into a variable for easier use, it doesn't work: 但是,当我将元素放入变量中以便于使用时,它不起作用:

var element={
    play:$(config.container).find('.'+config.play)
}

function clickHandler(){
    element.play.on('click',function(){
        console.log('clicked');
    }
}

Am I doing something incorrect here? 我在这里做错什么吗? Thanks. 谢谢。

The issue is that you are trying to access elements before they exist. 问题是您正在尝试访问元素,然后再访问它们。 In your top code example, the DOM elements are not being searched for until the clickHandler() function is executed. 在您的顶级代码示例中,在执行clickHandler()函数之前,不会搜索DOM元素。 Whereas in the bottom code example, it is trying to find the DOM elements immediately, and presumably, in your case, they don't exist yet. 而在底部的代码示例中,它试图立即查找DOM元素,并且在您的情况下,大概还不存在。

Here are a couple alternatives to solve your issue: 以下是解决问题的几种替代方法:

1) Event Delegation 1)活动委托

$(config.container).on('click', '.' + config.play,function(){
    console.log('clicked');
});

2) Turn element.play into a function 2)把element.play变成一个函数

var element={
    play: function () {
        return $(config.container).find('.'+config.play);
    }
}

function clickHandler() {
    element.play().on('click', ...);
}

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

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