为什么这个onClick事件在HTML iframe中不起作用?

时间:2016-02-17 13:34:04

标签: javascript html iframe

问题

我正在尝试使用onClick事件在用户点击iframe时进行注册。为什么这不起作用?

这是fiddle

代码

<html>
<head>
<script>

function myFunction() {
    document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</head>

<body onLoad="def()">
<iframe id="myFrame" border="0" onclick="myFunction()"></iframe>
<p id="demo"></p>

</body>
</html>

3 个答案:

答案 0 :(得分:1)

如果iframe来自您自己的网站,您可以写:

document.getElementById("myFrame")
    .contentWindow.document.body
    .onclick = function() {
        alert("iframe clicked");
    }

如果iframe来自与主页不同的域,则代码将无效。

答案 1 :(得分:0)

我不知道这是否适用于没有CORS或其他网站的网站,但是对于我需要的内容,这适用于具有不同ID的多个iframe -  https://jsfiddle.net/ab0a/1fyoajqc/6/

<!-- Multiple iframes with different IDs -->
<iframe id="iframe" src="https://livestream.com/accounts/5690925/events/6124324/player?width=960&height=540&enableInfoAndActivity=true&defaultDrawer=feed&autoPlay=true&mute=false" width="960" height="540" frameborder="0" scrolling="no" allowfullscreen></iframe>
<iframe id="iframetwo" src="iframe/here/too" width="960" height="540" frameborder="0" scrolling="no" allowfullscreen></iframe>
<iframe id="iframethree" src="iframe/here/as/well" width="960" height="540" frameborder="0" scrolling="no" allowfullscreen></iframe>
<div id="message"></div>

<script>
var monitor = setInterval(function() {
  var elem = document.activeElement;
  if (elem.id == 'iframe') {
    message.innerHTML = 'One';
    //use clearInterval(monitor); if you want to stop checking
    //clearInterval(monitor);
  }
  if (elem.id == 'iframetwo') {
    message.innerHTML = 'Two';
    //clearInterval(monitor);
  }
}, 100);

/* If you only want to check for a specific iframe once, but still want to check for others, set up another monitor for that specific iframe */
var monitorTwo = setInterval(function() {
  var elemTwo = document.activeElement;
  if (elemTwo.id == 'iframethree') {
    message.innerHTML = 'Three';
    message.style = 'background-color: red;';
    clearInterval(monitorTwo);
  }
})
</script>

答案 2 :(得分:-1)

我对以下JS更加满意:

root = ET.fromstring(xml_data)

for child in root:
    print(child.tag, child.attrib)


for sla in root.findall('Type'):
    goal = sla.find('Goal').text
    actual = sla.find('Actual').text
    compliant = sla.find('Compliant').text
    errors = sla.find('Errors').text
    checks = sla.find('Checks').text
    data=[goal,actual,compliant,errors,checks]
    df = pd.DataFrame(data)

    print(df)