编辑#2: 问题不存在了。这是某种范围界定问题。但现在它正在工作。对于给您带来的不便,我深表歉意。
在我的脚本的某些部分有一个事件委托并通过 id 指定目标。但是当我运行它时。这条线if(evt.target.id == ("subtaskSubmit" + subtaskCounter))
似乎根本不起作用。这是我的代码:
var subtaskCounter = 0;
aWholeTask.addEventListener("click", function(evt){
//other event targets specifications ..
if(evt.target.id == "divide"){
var subtaskInput = document.createElement("input"),
subtaskSubmit = document.createElements.button("submit"), // this is a special function i've made, don't bother about it. I've used it all over the place and it's working normally.
subtaskContainer = document.createElement("p");
subtaskContainer.style.marginLeft = "40px";
subtaskInput.id = "subtaskInput" + (++subtaskCounter);
subtaskInput.type = "text";
subtaskSubmit.id = "subtaskSubmit" + subtaskCounter;
subtaskContainer.appendChildren(subtaskInput,subtaskSubmit);
aWholeTask.appendChild(subtaskContainer);
}
if(evt.target.id == ("subtaskSubmit" + subtaskCounter)){
//this event is the one that not working when i press on that element
alert("hello");
}
});
编辑: 我做了一些更改来调试代码,结果很奇怪:
var subtaskCounter = 0;
aWholeTask.addEventListener("click", function(evt){
//other event targets specifications ..
if(evt.target.id == "divide"){
var subtaskInput = document.createElement("input"),
subtaskSubmit = document.createElements.button("submit"), // this is a special function i've made, don't bother about it. I've used it all over the place and it's working normally.
subtaskContainer = document.createElement("p");
subtaskContainer.style.marginLeft = "40px";
subtaskInput.id = "subtaskInput" + (++subtaskCounter);
subtaskInput.type = "text";
subtaskSubmit.id = "subtaskSubmit" + subtaskCounter;
subtaskContainer.appendChildren(subtaskInput,subtaskSubmit);
aWholeTask.appendChild(subtaskContainer);
}
if(evt.target.innerHTML == "Submit"){
alert(evt.target.id == ("subtaskSubmit" + subtaskCounter));
//And this surprisingly returns false !
}
});
那么为什么会evt.target.id == ("subtaskSubmit" + subtaskCounter)
退货false
呢?