Javascript 如何从iFrame中获取文本值
这是我的代码:Javascript 如何从iFrame中获取文本值,javascript,jquery,html,iframe,Javascript,Jquery,Html,Iframe,这是我的代码: <iframe src="http://www.golanpal.com/ahmad/test.txt" id="iframe" ></iframe> </br> <input type="button" value="Start" onclick="get()"> </br> <input id="textid" type="text"> <script language="JavaScript"
<iframe src="http://www.golanpal.com/ahmad/test.txt" id="iframe" ></iframe>
</br>
<input type="button" value="Start" onclick="get()">
</br>
<input id="textid" type="text">
<script language="JavaScript" type="text/javascript">
function get() {
?????????????
}
</script>
函数get(){
?????????????
}
text.txt文件中包含的值为(61.00%)
我想当按下开始按钮时,我想获取值(61.00%),并将其放入textinput(textid)
*请注意,示例中的值(61.00%)是可变的
问候语:)以下是如何使用香草JS。我已经将内联JS替换为更现代的JS技术 HTML
您可以在下面尝试,并确保访问同一域中的iframe
<script language="JavaScript" type="text/javascript">
function getPercent() {
var iframe = document.getElementById('iframe');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var percent = innerDoc.body.textContent.match(/(\d+\.\d+%)/g)
// ["17.00%", "0.00%", "61.00%"]
document.getElementById('textid').value = percent[2];
}
</script>
<iframe src="http://www.golanpal.com/ahmad/test.txt" id="iframe"></iframe>
</br>
<input type="button" value="Start" onclick="getPercent()">
</br>
<input id="textid" type="text">
函数getPercent(){
var iframe=document.getElementById('iframe');
var innerDoc=iframe.contentDocument | | iframe.contentWindow.document;
var percent=innerDoc.body.textContent.match(/(\d+\.\d+%)/g)
// ["17.00%", "0.00%", "61.00%"]
document.getElementById('textid')。值=百分比[2];
}
看起来像是thank you,,的副本,我可以让相同的代码在外部域上工作吗?对于外部域,使用XHR或jQuery Ajax,但远程服务器需要允许
// Cache the elements
const iframe = document.querySelector('#iframe');
const button = document.querySelector('button');
const input = document.querySelector('input');
// Add an event listener to the button
button.addEventListener('click', handleClick, false);
function handleClick() {
// Extract the textContent from the iframe content
const { textContent } = iframe.contentWindow.document.body;
// Update the input value
input.value = textContent;
}
<script language="JavaScript" type="text/javascript">
function getPercent() {
var iframe = document.getElementById('iframe');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var percent = innerDoc.body.textContent.match(/(\d+\.\d+%)/g)
// ["17.00%", "0.00%", "61.00%"]
document.getElementById('textid').value = percent[2];
}
</script>
<iframe src="http://www.golanpal.com/ahmad/test.txt" id="iframe"></iframe>
</br>
<input type="button" value="Start" onclick="getPercent()">
</br>
<input id="textid" type="text">