簡體   English   中英

切換什么觸發jQuery中的事件而無需重新加載?

[英]Switch what triggers an event in jQuery without reloading?

因此,我有一個網站,該網站加載開始時已暫停的GIF。 我有.on(“ event”)函數,它們分別在單擊和懸停時可以正常工作。 但是,我想讓用戶選擇他們要使用哪種方法通過設置播放gif。 我正在使用的代碼是這樣的:

if (hoverOn) {
    $(document).on("hover", ".content", function () {
        playTheGif();
    }
}
else {
   $(document).on("click", ".content", function () {
       playTheGif();

當然,單擊時它會暫停gif(如果已在播放)。

我有用於設置bool hoverOn的按鈕,該按鈕可以更改bool,但不會重新加載頁面,因此即使bool發生變化,播放gif的觸發器也保持不變。 有什么方法可以使if / else搜索在頁面中動態化?

謝謝,我希望自己能解釋清楚。

切換布爾測試和處理程序的位置,以便在處理程序內部測試布爾值:

$(document).on("hover", ".content", function () {
  if (hoverOn) playTheGif();
})
$(document).on("click", ".content", function () {
  if (!hoverOn) playTheGif();
});

我可能會嘗試將它們結合起來。

$(document).on("click mouseenter", ".content", function (e) {
    //do nothing for hoveron,click or hoveroff,hover
    if (hoverOn ^ e.type === "mouseenter") return;

    playTheGif();
});

 var hoverOn = true; $(document.body).on("click mouseenter", ".content", function (e) { //do nothing for hoveron,click or hoveroff,hover if (hoverOn ^ e.type === "mouseenter") return; //playTheGif(); $(e.target).css('backgroundColor', 'green'); }); $('button').on('click', function(){ hoverOn = !hoverOn; $('#interaction').text(hoverOn ? 'hover' : 'click' ); $('.content').css('backgroundColor', ''); }); 
 .content { display: inline-block; width: 150px; height: 150px; background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div> <button>Toggle Interaction</button> <span id="interaction">hover</span> </div> 

當用戶切換hoverOn時,可以取消設置當前事件並設置新事件。 例如:

if (hoverOn) {
    $(".content").unbind("click");
    $(document).on("hover", ".content", function () {
        playTheGif();
    }
}
else {
    $(".content").unbind("hover");
    $(document).on("click", ".content", function () {
        playTheGif();
    }
}

暫無
暫無

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

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