简体   繁体   English

将函数附加到动态创建的DOM元素

[英]Attach function to dynamically created DOM element

Goal: 目标:

Append a DOM element with functionality. 附加具有功能的DOM元素。 (One global listener is not desire here.) (这里没有一个全球性的倾听者。)

Problem: 问题:

I don't know how to reference the new element in this context. 我不知道如何在这种情况下引用新元素。 The problem area is the .on event listener and the references to $(this) contained inside. 问题区域是.on事件侦听器以及其中包含的对$(this)的引用。 Also, the ability for the function get_value() to call itself again from within. 另外,函数get_value()可以从内部再次调用自身的功能。

Relevant Code: 相关代码:

var dom_element = (function() {
    // [...]
    var create = function create( data ) {
        // [...]
        return $('<div />', { 'class': 'element', id: data.i_id })
            // [...]
            .on('load', function get_value() {
                // [...]
                $(this).find('.value').text(s_value);
                // [...]
                setTimeout('get_value()', 5000);
            }());
    },
    // [...]
    return {
        create: create
    };
}());

The load event won't work on a <div> element. load事件不适用于<div>元素。

If you want to perform some action when the content of the div is updated, you should do so in the code that updates the content. 如果要在更新div的内容时执行某些操作,则应在更新内容的代码中执行此操作。

var dom_element = (function() {
    // [...]
    var create = function create( data ) {
        // [...]
        var div =  $('<div />', { 'class': 'element', id: data.i_id })
            // [...]
        (function get_value(div) {
            // [...]
            $(div).find('.value').text(s_value);
            // [...]
            setTimeout(function() {
                get_value(div);
            }, 5000);
        })(div);

        return div;
    },
    // [...]
    return {
        create: create
    };
}());

I updated the code to do what I assume you're looking for. 我更新了代码以执行假设您要查找的操作。

As another had said, on.('load'...) doesn't apply here. 正如另一个人所说,on。('load'...)在这里不适用。 You're creating these elements dynamically (presumably after the DOM is all ready) so you should be able to start the timeouts right away. 您正在动态创建这些元素(大概是在DOM准备就绪之后),因此您应该能够立即开始超时。 Here's my take: 这是我的看法:

var make_new = function(data){
    var $div = $('<div>', {'class': 'element', 'id':'element_'+data});
    var func = function(){
        // closure has formed around data, $div, and func
        // so references to them here reference the local versions
        // (the versions outside this immediate function block. i.e,
        // inside this call of make_new)
        data++;
        $div.text($div.attr('id') + ":" + data);
        setTimeout(func, 1000);
    };
    func();  //start process rolling
    return $div;
};

Basically, you should take advantage of js closures to capture the references that you need. 基本上,您应该利用js闭包来捕获所需的引用。 func() is called before returning the div element, but there's nothing stopping you from returning both the element and func, and calling func() later. 在返回div元素之前会先调用func(),但是没有什么阻止您同时返回该元素和func,并稍后再调用func()。

Check out the jsfiddle of this here: http://jsfiddle.net/gRfyH/ 在这里查看jsfiddle: http//jsfiddle.net/gRfyH/

The scope of a event handler is always the element, so using this you're doing everything right to reference the created <div> from get_value . 事件处理程序的范围始终是元素,因此使用this您将做一切正确的事情,以引用get_value创建的<div>

Yet, when you call get_value from the timeout, it will be executed in the global context. 但是,当您从超时中调用get_value时,它将在全局上下文中执行。 So you need to bind() the function to the element before passing it in setTimeout : 因此,您需要在setTimeout传递函数之前将函数bind()到元素:

setTimeout(get_value.bind(this), 5000);

Or you do it manually: 或您手动进行:

var el = this;
setTimeout(function() {
    get_value.call(el);
}, 5000);

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

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