将 .has() 与 keyup 事件一起使用

Using .has() with keyup event

本文关键字:事件 一起 keyup has      更新时间:2023-09-26

我正在尝试使用.has()选择器仅在我的身体有图像时才执行键控制。

这就是我目前正在尝试的,但它不起作用。

if ($('body').has('img')){
   $(document).on('keyup', function (event) {
     if (event.which === 37) {
       console.log('test');
     }
   });
}

试试这个

if ($('body img').length) {
}

我宁愿使用普通选择器检查图像是否存在:

if ($('img').length) {
   $(document).on('keyup', function (event) {
     if (event.which === 37) {
       console.log('test');
     }
   });
}

这是工作小提琴

如果可以将 hanlder 注册到 body 元素并且图像条件是动态的,那么

$(document).on('keyup', 'body:has(img)', function (event) {
    if (event.which === 37) {
        console.log('test');
    }
});

为什么不:

$(document).on('keyup', 'body', function (event) {
    if($(this).find('img').length) {
       if (event.which === 37) {
           console.log('test');
       }
    }
});