事件中自定义属性的“未定义”值(Firefox)

时间:2012-12-15 11:28:29

标签: javascript firefox iframe javascript-events undefined

我的test.html页面包含代码(https://gist.github.com/4293833):

<!doctype html>
<html>
<head>
  <script>
  var paymentEventHandler = function (e) {
    console.log(e)
    console.log('payment: ' + JSON.stringify(e.status))
    alert('status: ' + e.status)
  }

  if (document.addEventListener) {
    document.addEventListener('payment', paymentEventHandler)
  } else {
    document.attachEvent('onPayment', paymentEventHandler)
  }
  </script>
</head>
<body>
  <iframe src='/iframe.html'></iframe>
</body>
</html>

和iframe.html:

<!doctype html>
<html>
    <head>
        <script>
         var event

         if (document.createEvent) {
             event = document.createEvent("HTMLEvents")
             event.initEvent("payment", true, true)
         } else {
             event = document.createEventObject()
             event.eventType = 'payment'
         }

         event.status = 'ok'

         if (window.parent.document.dispatchEvent) {
             window.parent.document.dispatchEvent(event)
         } else {
              window.parent.document.fireEvent('onPayment', event)
         }
        </script>
    </head>
    <body>
    </body>
</html>

代码适用于Chrome,Safari,Opera,但在Firefox中我获得了undefined。为什么呢?

谢谢。

1 个答案:

答案 0 :(得分:2)

您需要创建自定义事件而不是htmlevent并使用initCustomEvent初始化

的HTML

    <!doctype html>
    <html>
    <head>
      <script>
      var paymentEventHandler = function (e) {
        alert('status: ' + e.detail.status)
      }

      if (document.addEventListener) {
        document.addEventListener('payment', paymentEventHandler)
      } else {
        document.attachEvent('onPayment', paymentEventHandler)
      }
      </script>
    </head>
    <body>
      <iframe src='iframe.html'></iframe>
    </body>
    </html>

的iframe

    <!doctype html>
    <html>
        <head>
            <script>
             var event

             if (document.createEvent) {
                 event = document.createEvent("CustomEvent")
                 event.initCustomEvent("payment", true, true, {status:"ok"});
             } else {
                 event = document.createEventObject()
                 event.eventType = 'payment'
             }

             if (window.parent.document.dispatchEvent) {
                  console.dir(event);
                 window.parent.document.dispatchEvent(event)
             } else {
                  console.dir(event);
                  window.parent.document.fireEvent('onPayment', event)
             }
            </script>
        </head>
        <body>
        </body>
    </html>