从具有值的表单中删除输入元素会导致网站崩溃

Removing input element from form that has a value result in website crash

本文关键字:元素 崩溃 网站 输入 删除 表单      更新时间:2023-09-26

我有一个包含一系列输入字段的表单,我还用javascript动态添加输入字段到这个表单中。我正试图用以下代码动态删除这些元素:

var catchMarkers = [];
var fishingtripMarker;
var catchIdCounter = 0;
function placeCatchMarker(position)
{
catchMarker = new google.maps.Marker({
    position: position,
    map: map,
    draggable: true,
    animation: google.maps.Animation.DROP
});
catchMarker.set("id", catchIdCounter);
AddCatchInput(catchIdCounter);
catchIdCounter++;
//Right click listener
markerListener = google.maps.event.addListener(catchMarker, 'rightclick', function(event) {
    //removing inputs from form
    var fish = document.getElementById('Fish'+this.get("id"));
    var weight = document.getElementById('Weight'+this.get("id"));
    fish.parentNode.removeChild(fish);
    weight.parentNode.removeChild(weight);
    //removing marker
    this.setMap(null);
    var index = catchMarkers.indexOf(this);
    catchMarkers.splice(index, 1);
});
catchMarkers.push(catchMarker);

}

我用以下代码创建这些输入字段:

function AddCatchInput($id)
{
var container = document.getElementById("myform");
var select = document.createElement("select");
select.setAttribute("id", "Fish"+$id);
var option;
option = document.createElement("option");
option.setAttribute("value", "1");
option.innerHTML = "Trout";
select.appendChild(option);
var input = document.createElement("input");
input.id = "Weight" + $id;
container.appendChild(select);
container.appendChild(input);
}

一切都很好,直到我试图删除这些输入字段时,任何表单的输入字段都有值,然后网站崩溃了,我不知道为什么。

这显然是一个与右键单击事件有关的bug(在chrome中)。

问题不在于输入有一个值,而是当你右键点击标记时,输入有焦点时,就会发生这种情况,崩溃演示:http://jsfiddle.net/doktormolle/57V72/

可能的解决方案:在右键点击触发之前将焦点从输入中移除,例如onmousedown:

google.maps.event.addListener(catchMarker, 'mousedown', function (event) {
    document.getElementById('Weight' + this.get("id")).blur();
});

没有崩溃的演示:http://jsfiddle.net/doktormolle/57V72/1/

你应该报告这个错误。