2017-06-19 103 views
1

我正在创建一个以Google Maps Javascript API为中心的应用程序,并使用了信息框插件。on无法识别添加的链接元素

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

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用户界面自动完成构件的另一个功能,它工作得很好:

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

使用[委派事件处理(https://learn.jquery.com/events/event-delegation/) – James

+1

@詹姆斯,这是他们在做什么。 – trincot

+0

@詹姆斯他是。我认为这个问题与html内部的google地图iframe有关。不完全确定。 – Goose

回答

0
  1. $(文件),而不是$( '文件') - 虽然这很可能是不会导致问题 - #2是。
  2. 这假定按钮在页面加载时位于DOM中。 (“click”,“.adduser”,function(){ alert('hello world!'); });

如果我正确阅读您的标记和脚本,这不是正确的。所以,你不能绑定页面加载后使用该方法的点击事件。您将需要使用委派。

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

是不是代表已弃用赞成on? –

+0

是的 - 它实际上取代了其他几种方法 - 但委托仍然工作得很好。 – Korgrue