jquery:回调函数可以知道它连接到哪个节点吗?

toe95027  于 12个月前  发布在  jQuery
关注(0)|答案(1)|浏览(94)

我将回调函数附加到每个查询结果对象的数据属性(几个!),如下所示:

$(".myclass").data('callback', (node, value) => {
    console.log("Callback called on node with id: " + node.attr('id'));
    // do something with value
});

// When called, the actual node the callback is attached to needs to be passed as well:

let callback = node.data('callback');
callback(node, 123);

字符串
有没有可能这个函数一旦被调用,就知道它属于哪个节点?类似于一个闭包,存储对每个查询对象的引用。显然,this$(this)不起作用。
种类:

$(".myclass").data('callback', (value) => {
    let node = respective query result object;
    console.log("Callback called on node with id: " + node.attr('id'));
    // do something with value
});

...

let callback = node.data('callback');
callback(123);


也许类似于jquery的on()bind(),但这些仅限于事件,而不是可以从外部调用的自定义函数。

inkz8wg9

inkz8wg91#

给你两个选择:
1.使用事件系统
1.编写一个插件

使用事件系统

通过事件系统而不是通过data存储函数来实现这一点:
1.为您自己的自定义事件附加处理程序
1.使用一个传统的函数,这样jQuery就可以在调用它时将this设置为元素
1.接受两个参数:事件和要传递的额外值
1.通过trigger“调用”回调
示例如下:

// Notice we're using a traditional function, not an arrow function
$(".myclass").on("callback-event", function (event, value) {
    // In the function, `this` refers to the DOM element the event
    // was triggered on. (Note it's not a jQuery wrapper.)
    console.log(
        `Callback called on node with id: ${this.id} with value ${value}`
    );
});

const elements = $(".myclass");
const node = $(elements[Math.floor(Math.random() * elements.length)]);

// Calling the callback
node.trigger("callback-event", 123);

个字符
这也为您提供了将多个“回调”(也就是说,事件处理程序)附加到事件的选项。

编写插件

你可以写一个插件来把你自己的函数附加到jQuery对象上,这个函数不仅存在于特定的jQuery对象上,而且你可以让它像它一样工作。

// Basic plugin template with your function in it
(($) => {
    // This needs to be a traditional function, not an arrow function,
    // so `this` can be set by how it's called
    $.fn.callback = function(value) {
        // Here, `this` is the jQuery object which may have multiple
        // elements (or none) in it
        // You can filter out elements that don't have your class
        // on them if you like; otherwise, just remove the `filter`
        // call here and use `this.each(...)`.
        this.filter(".myclass").each((_, element) => {
            // Here, `element` is a DOM element
            console.log(
                `Callback called on node with id: ${element.id} with value ${value}`
            );
        });
        return this;
    };
})(jQuery);

const elements = $(".myclass");
const node = $(elements[Math.floor(Math.random() * elements.length)]);

// Calling the callback
node.callback(123);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one" class="myclass">one</div>
<div id="two" class="myclass">two</div>
<div id="three" class="myclass">three</div>

的字符串

相关问题