j查询 iframe 和警报中的目标 ID



我的代码如下所示。

<!DOCTYPE html>
<html>
<head>
<title>TODO</title>
</head>
<body>
<div id="btn">
<button id="clickme">Click Me</button>
</div>
<div class="iframebox">
<iframe id="messageiframe">
<html>
<head>
<title>test</title>
</head>
<body>
<div id="textpreview">
<p id="pre">some text</p>
</div>
</body>
</html>
</iframe>
</div>
</body>
</html>

我正在尝试使用jQuery在iframe中定位id="textpreview"。我可以成功地定位 iframe 外部的任何 id,但无法定位 iframe 内部。

我的jQuery代码是:

$('#clickme').on('click', function() {
if ($("#textpreview").length > 0) {
alert("success");
}
});

我怎样才能做到这一点?

提前谢谢。

使用 "content((">

$("#messageiframe").contents().find("#textpreview")

https://api.jquery.com/contents/

<!DOCTYPE html>
<html>
<head>
<title>TODO</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<div id="btn">
<button id="clickme">Click Me</button>
</div>
<div class="iframebox">
<iframe id="messageiframe">
<html>
<head>
<title>test</title>
</head>
<body>
<div id="textpreview">
<p id="pre">some text</p>
</div>
</body>
</html>
</iframe>
</div>
</body>
<script>
$('#clickme').on('click', function() {
if ($("#textpreview").has("pre")) {
alert("success");
}
});
</script>
</html>

检查它是否有 ID。

最新更新