Document.onclick 运行 两次

Document.onclick running twice

我正在尝试通过 javascript 将 mailto link 添加到工具提示中的元素。我必须将代码放在 document.onclick 中,因为代码不会 运行 如果不是。所以现在我可以正常工作了,但问题是您需要在 link 上单击两次才能触发。有没有办法删除 2 次点击?如果此功能不在 document.onclick 内,则它不起作用。提前致谢..

document.onclick = function(){
     jQuery(".gm_popup .email").click(function(){
        var text = jQuery(this).text();
        document.location = "mailto:" + text.trim();
    });
  }

与其在单击时将事件附加到您的元素,不如在页面加载时附加它。由于您已经在使用 jquery:

$(function() {
    //Anything you place in here won't be run until the page has loaded
});

所以,在你的情况下,做这样的事情

$(function() {
    jQuery(".gm_popup .email").click(function(){
        var text = jQuery(this).text();
        document.location = "mailto:" + text.trim();
    });  
});

不确定是否要单击元素以便工具提示显示 link,然后在工具提示中第二次单击 link。 除此之外,你可以试试:

$(document).ready(function() {
$(".gm_popup .email").click(function(event){
        event.preventDefault();
        var text = jQuery(this).text();
        document.location = "mailto:" + text.trim();
    });
});

希望对您有所帮助!

您似乎想在显示时将 mailto 事件处理程序添加到工具提示 link,因此您在单击文档时将事件绑定到 link。在这种情况下,也许 $(".gm_popup .email").on("click", handler) 是更好的选择。

成功了

$(document).on('click', '.gm_popup .email', function(){
  var text = jQuery(this).text();
  document.location = "mailto:" + text.trim();
});