我有 test.php
文件,其中包含 iframe,当单击按钮 click
时,该文件从 iframe.html
获取其源代码。
但是我想在 iframe (iframe.html
) 内的文件元素上应用一些 javascript 代码,但什么也没发生,这是我的代码:
tesp.php 文件:
<html>
<head>
<title>test</title>
</head>
<body>
<input type="button" value="Click" id="fill_iframe"/>
<br>
<iframe id="iframe" src="" style="width: 200px; height: 100px">hello</iframe>
<br>
<div class="front">
<a href="#">outside frame</a>
</div>
<br>
<input type="button" value="change color" id="log"/>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script>
$("#fill_iframe").click(function () {
$("#iframe")[0].src = "iframe.html";
});
$("#log").click(function () {
$('.front a').css('color', 'red');
console.log($("#iframe"));
});
</script>
</body>
</html>
和 iframe.html 文件:
<html>
<head>
</head>
<body>
<div class="front">
<a href="#">inside frame</a>
</div>
</body>
</html>
当我单击更改颜色
按钮时,仅更改外部链接。
当我使用 console.log($("#iframe"));
时,它没有子项?这是为什么?
我错过了什么?
我什至尝试使用 $("#iframe").load("iframe.html");
没有任何改变
提前致谢:)
最佳答案
您需要进入 iframe 文档内部。在 jQuery 中,您可以使用
jQuery("#iframe").contents().find(".front a").css("color", "red");
关于javascript - 将iframe内html文件的元素添加到原始文件的DOM树中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41665499/