gpt4 book ai didi

javascript - 获取 jQuery 的 .on() 数据对象中的 $(this) 访问权限?

转载 作者:行者123 更新时间:2023-12-02 18:10:54 26 4
gpt4 key购买 nike

我正在使用 .on() 在我的 DOM 中添加一些监听器 - 一个输入范围字段和一些带有 .colorBlock 类的 block 。这些事件监听器只需要间歇性地事件,我想在不使用它们时将它们关闭 .off() 。这样做意味着使用命名函数而不是匿名函数。

很公平,只是我需要将数据传递到回调函数中。我知道我可以使用第二个(第三个?)参数字段将对象传递给事件,该对象在回调中可读,但这样做似乎将 this 范围限定为 事件,而不是 .on() 监听的 DOM 节点。请参阅下面的示例:

$('#brushSize').on('touchend', { size: $(this).val() }, utils.setBrushSize);
$('.colorBlock').on('touchstart', { color: $(this).data('color') }, utils.setColor);

在我的回调函数中,我添加了 e.data.color 和 e.data.size 的警报,并且都调用了未定义

更糟糕的是,这是一个电话间隙应用程序,因此我在跟踪正在传递的内容时的选择受到限制,因此我假设的一些内容可能是错误的。

有什么建议吗?

谢谢。

最佳答案

让我们分解一下这一行:

$('#brushSize').on('touchend', { size: $(this).val() }, utils.setBrushSize);

与此完全相同(除了变量之外):

var sizeValue = $(this).val();
$('#brushSize').on('touchend', { size: sizeValue }, utils.setBrushSize);

例如,您正在调用 $(this).val(),然后将调用它的结果作为数据对象的一部分传递。因此,除非 this 已经是您此时想要从中获取值的内容,否则它不会起作用。

如果您想在事件发生时从元素获取一些信息,只需将该代码放入事件处理程序中即可。例如,查看这一行:

$('.colorBlock').on('touchstart', { color: $(this).data('color') }, utils.setColor);

在我看来,您正在尝试从触摸的 .colorBlock 元素中获取颜色。如果是这样:

$('.colorBlock').on('touchstart', function() {
utils.setColor($(this).data('color'));
});

或者如果您要重复使用它:

utils.setColorFromEventElement = function() {
utils.setColor($(this).data('color'));
};

$('.colorBlock').on('touchstart', utils.setColorFromEventElement);
<小时/>

旁注:

该行还可能存在第二个问题。您使用 utils.setBrushSize 作为事件处理程序。请注意,在对 setBrushSize 的调用中,this 将引用您 Hook 事件的 DOM 元素,而不是 utils。现在,考虑到名称 utils,也许这并不重要,但我想我应该提到它。

更多:Mythical methods , You must remember this

关于javascript - 获取 jQuery 的 .on() 数据对象中的 $(this) 访问权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19723025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com