javascript - Vanilla JS 中的事件定位与 jQuery 中的事件定位

标签 javascript jquery targeting

我正在做事件定位实验并比较它在 vanilla JS 和 jQuery 中的执行情况。我很惊讶结果不同;它在 vanilla JS 中取得了成功,但在 jQuery 中却不然。如果我没记错的话,jQuery 中事件定位的代码是 $(event.target)在普通 JS 中是 event.target 。在我的实验中,我只有 <body> 内有一个按钮标签,每当它成为事件的目标时,浏览器都应该警告“按钮元素是目标”,否则它将是“窗口本身是目标”。但即使目标元素是按钮,警报通知也只是“窗口本身被定位”。这是我的代码:

普通 JS

let $ = document.querySelector.bind(document);

window.onclick = function(event) {
    if(event.target != $('button')) {
        alert('window itself is targeted');
    } else {
        alert('button element is targeted');
    }
}

jQuery

$(window).on('click', function(event) {
    var $eventTarget = $(event.target);

    if($eventTarget != $('button')) {
        alert('window itself is targeted');
    } else {
        alert('button element is targeted');
    }
});

在 jQuery 代码中,我尝试替换 $(event.target)event.target看看它的执行是否与普通 JS 类似,但没有任何改变。是我的代码的语法导致它失败还是有其他我没有注意到的错误。希望有人能指点一下。

最佳答案

您的测试存在缺陷,因为当您比较 DOMElement 和 jQuery 对象时, event.target != $('button') 始终为 true,并且 $eventTarget != $('button') 也将始终为 true,因为您无法直接比较对象。

要修复此比较对象的属性:

// Native:
let $ = document.querySelector.bind(document);
window.addEventListener('click', function(e) {
    if (e.target.id != $('button').id) {
        alert('window itself is targeted');
    } else {
        alert('button element is targeted');
    }
});

请注意此处首选使用 addEventListener(),而不是 onclick()

Working native example

// jQuery
$(window).on('click', function(e) {
    if (e.target.id != $('button').prop('id')) {
        alert('window itself is targeted');
    } else {
        alert('button element is targeted');
    }
});

Working jQuery example

关于javascript - Vanilla JS 中的事件定位与 jQuery 中的事件定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41160593/

相关文章:

cookies - Cookie 同步 : user id mapping between different cookie domains

android - 使用 CSS 定位 Android 移动设备 (Galaxy S)

javascript - 导航菜单

javascript - 数据列表获取选定值和自定义属性(无事件)

javascript - 来自输入的字符串和运行时的字符串不相等?

javascript - 如何使用 jQuery 将 html block (<ul>) 直接放置在 &lt;input&gt; 下?

php - 动态添加/删除新的表单输入

javascript - jquery ui Accordion 不自动高度

jquery - 在 TBODY 中第一个 TR 的最后一个 TD 中定位 anchor href

javascript - 尝试使用 Spotify Web Api 将歌曲添加到另一个协作播放列表时出现 403 禁止错误