event.target.id.indexOf(" foo")不工作 - 在IE中不工作

时间:2015-01-29 12:24:25

标签: javascript html javascript-events indexof

我有一个JavaScript函数,它循环遍历类并获取一个ID,我将其包含在名为' item'的div中。一旦他们点击一个按钮,它就会通过我已经包含信息的div冒泡并收集ID。例如:

output = "<div id='item" + json_output[i].id + "'>" +
  "<div class = 'itemBoxes'>"+
  "<h3 class ='itemTitle'>" +json_output[i].classname + "</h3>" +
  "<div class = 'paddingBottom'></div>" +
  "<p class = 'itemDesc'>" + json_output[i].classdescription + '</p>' +
  "<div class ='itemInfo'>" +
  "<div class ='bookingItems'> <img src = 'img/glyphicons-268-credit-card.png'</img> <p class = 'itemDetails'>£" + json_output[i].classprice + "</p></div> "+
  "<div class ='bookingItems'> <img src = 'img/glyphicons-46-calendar.png'</img> <p class = 'itemDetails'>" + json_output[i].classdate + "</p></div>" +
  "<div class ='bookingItems'> <img src = 'img/glyphicons-55-clock.png'</img><p class = 'itemDetails'>"+ json_output[i].classstarttime +"</p></div>" +
  "<div class ='bookingItems'> <img src = 'img/glyphicons-44-group.png'</img><p class = 'itemDetails'>" + json_output[i].classparticipants + " spaces </p></div>" +
  "</div>" +
  "<p id ='bookingBox'> <input type='button' class='bookingSubmit' value='Book Now'/> </p>" +
  "</div>" +
  "</div>";
  target.innerHTML += output;

我用来查找ID的代码是:

var fetchModifyButton;
//Gets the button that says 'Modify'
fetchModifyButton = _c("bookingSubmit");
//Remove Button.
for (var i = 0, j = fetchModifyButton.length; i < j; i++) {
    fetchModifyButton[i].addEventListener("click", function () {
      var e, productID, newID;
        //Bubbles up and finds the ID of the product they want to modify
        e = event.target;
        while (e.id.indexOf('item') == -1) {
            e = e.parentNode;
        }
        productID = e.id;
        //Removes everything but the numbers.
        newID = productID.replace(/[^0-9.]/g, "");
        getClassInfoForBooking(newID, newID);
    });
}

这适用于Google Chrome,IE11和大多数其他浏览器。

它在IE8,9或10中不起作用。

我收到的错误信息是:

SCRIPT5007:无法获得财产&#39; id&#39;未完成或空引用 然后它指向行:while(e.id.indexOf(&#39; item&#39;)== -1){

我想知道是否有人有任何想法?太棒了,谢谢!

1 个答案:

答案 0 :(得分:0)

使用event.srcElement进行IE

var addEvent =  window.addEventListener||window.attachEvent;
fetchModifyButton[i].addEvent("click", function () {
    var e, productID, newID;
    //Bubbles up and finds the ID of the product they want to modify
    e = event.target||event.srcElement;
    while (e.id.indexOf('item') == -1) {
        e = e.parentNode;
    }
    productID = e.id;
    //Removes everything but the numbers.
    newID = productID.replace(/[^0-9.]/g, "");
    getClassInfoForBooking(newID, newID);
});