簡體   English   中英

使用.has()和keyup事件

[英]Using .has() with keyup event

我試圖使用.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');
       }
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM