【问题标题】:on doesn't recognize added link elementon 不识别添加的链接元素
【发布时间】:2017-06-19 20:13:39
【问题描述】:

我正在创建一个以 Google Maps Javascript API 为中心的应用程序,并且我正在使用 infobox 插件。

创建信息框的函数的代码:

var ibOptions = {
    disableAutoPan: false,
    zIndex: null,
    infoBoxClearance: new google.maps.Size(1, 1),
    pixelOffset: new google.maps.Size(-85, -290),
    isHidden: false,
    pane: "floatPane",
    enableEventPropogation: true
};


let marker = new google.maps.Marker({
    icon: icon,
    map: map,
    draggable: true,
    position: new google.maps.LatLng(latlng.lat, latlng.lng),
    visible: true
});

boxText.innerHTML = "<input type='text' id='user' placeholder='Add User' />"
                    + "<a href='#' class='adduser'>Add User</a>";
ibOptions.content = boxText;

let ib = new InfoBox(ibOptions);

ib.open(map, marker);

然后在另一个函数中,我试图捕获对信息框内按钮的单击,但没有发生任何事情。控制台中没有错误,也没有警报。我可以在我的 adduser 函数中记录一些琐碎的消息,这样我就知道其他一切都在正常工作,并且我确实确保导入 jQuery。

export function addUser() {
    $("document").on("click", ".adduser", function () {
        alert('hello world!');
    });
};

我有另一个调用 jquery ui 自动完成小部件的函数,它工作得很好:

$("#user").autocomplete({
    source: userArray
});

【问题讨论】:

  • @James,他们就是这么做的。
  • 使用 $(document) 而不是 $("document")
  • 你调用函数了吗?点击之前喜欢addUser()
  • @VasiliyGorokhov,jQuery 也将"document" 识别为选择器。

标签: javascript jquery google-maps


【解决方案1】:
  1. $(document),而不是 $('document') - 虽然这可能不会导致问题 - #2 是。
  2. 这假定按钮在页面加载时位于 DOM 中。 $("document").on("click", ".adduser", function () { alert('你好世界!'); });

如果我正确阅读了您的标记和脚本,情况并非如此。因此,您无法使用该方法在页面加载后绑定单击事件。您将希望使用委托。

$('#yourButtonWrapper').delegate('.adduser', 'click', function() { 
  alert('hello world!');
});

【讨论】:

  • 代理不是被弃用了吗?
  • 是的 - 它实际上替换了其他几种方法 - 但委托仍然可以正常工作。
猜你喜欢
  • 1970-01-01
  • 2011-04-22
  • 2011-07-29
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
相关资源
最近更新 更多