簡體   English   中英

在JavaScript創建的元素上觸發鼠標懸停

[英]trigger mouseover on element created by JavaScript

按下按鈕並偵聽這些鏈接的鼠標懸停事件時,需要創建鏈接。

我使用此函數創建鏈接:

function newlink(){  
  var a = document.createElement('a');
  var linkText = document.createTextNode("Test");   
  a.appendChild(linkText);
  a.href ="Page.html";   
  a.setAttribute("class","trigger");
  document.getElementById('divID').appendChild(a);
};

在體內,我有這個按鈕:

<input type="button" value="Show Link" onClick="newlink()">

在頭部,我具有此功能來攔截鼠標懸停:

$(function(){
  $('a.trigger').hover(  
    function(e) {       
       alert ('Mouse over intercepted');
       ...  
  });
});

當我單擊按鈕時,將正確創建鏈接,但不會生成mouseover事件。 有什么問題?

要將事件附加到動態創建的HTML元素,請使用JQuery的.on()方法。

使用.on() ,如下所示:

$(document).on('mouseover','a.trigger',function(){
    alert('Mouse over intercepted');
});

如果您是我,那么在創建鏈接時,我會添加邏輯,而不是稍后通過JQuery添加邏輯。

您的代碼將如下所示:

function newlink(){  
  var a = document.createElement('a');
  var linkText = document.createTextNode("Test");   
  a.appendChild(linkText);
  a.href ="Page.html";   
  a.setAttribute("class","trigger"); // <-- you probably don't need this anymore
  a.onmouseover = function() {
     // ... here is your logic !!!
  }
  document.getElementById('divID').appendChild(a);
};

.hover()是一個快捷的mouseenter鼠標離開事件,所以你可以使用使用事件代表團。對()以注冊MouseEnter事件處理程序和鼠標離開的動態添加內容的事件。

function newlink(){  
    $('<a href="Page.html" class="trigger">Test</a>').appendTo('#divID');
};

$(function(){
    $('#divID').on('mouseenter', 'a.trigger', function(){
        console.log('entered')
    })
})

暫無
暫無

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

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