[英]Chrome event registered with addEventListener not firing on 'click'
我使用js開發了一個小型Web應用程序。 該應用程序在mozilla ff瀏覽器中可以正常運行。 在窗口加載時觸發ajax請求,成功后會更改dom-包括一個小的select元素並為其添加選項,每個選項都獲得一個eventListener。 以下是一些相關摘錄:
var lst = null;
window.onload=init;
function init() {
$.ajax({
data : {
type : 'someType',
sender : 'someSender'
},
beforeSend : function () {
},
success : function (response) {
response = JSON.parse(response);
if (response.links.constructor === Array) {
dispNavList(document.getElementById("navProxy"), response.links);
atch();
}
if (response.data.constructor === Array) {
dispTable(document.getElementById("dataProxy"), response.data);
if (response.data.length > 0) {
setTimeout("refresh()", 1000);
}
}
},
complete : function () {
}
});}
function dispNavList(proxy, v) {
if (lst != null) {
dtch();
lst = null;
}
proxy.innerHTML = null;
if (v.length > 0) {
lst = document.createElement('select');
var i = 0;
while (i < v.length) {
var opt = document.createElement('option');
opt.setAttribute('value', v[i].ename);
opt.appendChild(document.createTextNode(v[i].dscr));
lst.appendChild(opt);
i = i + 1;
}
proxy.appendChild(document.createElement("p").appendChild(document.createTextNode('Data fetched @:' + timenow())));
proxy.appendChild(lst);
} else {
proxy.appendChild(document.createElement("p").appendChild(document.createTextNode('Data fetch failed @:' + timenow())))
}}
function atch() {
if (lst != null) {
var options = lst.querySelectorAll("option");
if (options.length != "undefined") {
[].forEach.call(options,
function (e) {
console.log('inside');
e.addEventListener('click', caller,false);//.bind(e), false);
})
}
}}
function caller(event) {
console.log(event.target.nodeType);
return;
/*var arr = {
type : 'd',
sender : this.getAttribute('value')
};
$.ajax({
data : arr,
beforeSend : function () {
clearTimeout(aTout);
aTout = null;
},
success : function (response) {
clearTimeout(aTout);
aTout = null;
response = JSON.parse(response);
if (response.links.constructor === Array) {
dispNavList(document.getElementById("navProxy"), response.links);
atch();
}
if (response.data.constructor === Array) {
dispTable(document.getElementById("dataProxy"), response.data);
//alert(response.data.length);
if (response.data.length > 0) {
setTimeout("refresh()", 1000);
}
}
},
complete : function () {
}
}
});*/}
dtch()函數與atch()刪除事件偵聽器相反。 那里有一些注釋,因為我首先嘗試將此對象綁定到選項(在atch()函數中),並且它成功地做到了,而調用方函數起初沒有參數(事件-我已經嘗試過以下操作) (例如在線圖書中的示例),它只是適當地識別了該對象(冒充)。 問題在於,盡管eventListener已正確連接(在開發人員工具中已選中),但單擊時未調用caller()。 如果缺少某些內容(代碼,其他信息等),請詢問,我將提供它們。 還請忽略其他注釋的代碼,該應用程序正在構建中,我正在嘗試各種方法。 即使有小的語法錯誤,我也保證我有ffox的有效代碼。
很抱歉張貼重復的問題。 您可以在firefox中獲得答案@ addEventListener,但不能在chrome中使用 。 因此,將事件類型更改為select元素上的“ change”,並通過以下方式獲取選項
selectElement.options[selectElement.selectedIndex].value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.