[英]Javascript input data from a link into text field within an iFrame
下午好。
<iframe width="550" id="iframe1" height="350" scrolling="no" src="blah.com/iframe.html"></iframe>
<script type="text/javascript">
function insertTxt() {
var textstring = "";
parent.iframe1.document.getElementsByTagName("input")[0].value = textstring;
}
</script>
<a href="#" onclick="insertTxt();">test 1</a>
<a href="#" onclick="insertTxt();">test 2</a>
<a href="#" onclick="insertTxt();">test 3</a>
<a href="#" onclick="insertTxt();">test 4</a>
在iframe中加載的頁面具有1個輸入字段,但沒有ID可鎖定。 我一直在尋找解決方案,以使其正常工作。 我正在嘗試獲取文本“ test 1”或“ test 2”等,以將其插入到iframe中的此輸入字段中。
在iframe文件中,這是輸入字段html。
<input type="text" autocomplete="off" spellcheck="true" maxlength="361" style="width: 100%; padding: 0px; border: 0px; margin: 0px; outline: 0px; background: rgb(255, 255, 255); color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 15px;">
如果有人能夠幫助我解決上述問題。
非常感激。
首先,您將空白字符串分配給變量textstring,其次,如果在沒有網絡服務器的情況下執行此操作將不起作用(在控制台中將收到錯誤Uncaught DOMException
)。
請按照以下步驟操作
name="iframe1"
<a href="#" onclick="insertTxt(this);">test 1</a>
將功能更改為
function insertTxt(el) { var textstring = el.text; parent.iframe1.document.getElementsByTagName("input")[0].value = textstring; }
為此,您可能需要配置服務器,否則會收到CORS錯誤。
我在這里使用querySelector,但它也應該與elementsByTagName和id一起使用。
iFrame.document是未定義的,但是您可以像這樣獲取iFrame的內容。 如果您在執行此操作時沒有遇到任何錯誤,那么您就很好了。
var iFrame = document.querySelector('#frame1'),
iFrameContent = iframe.contentDocument || iframe.contentWindow.document;
然后,您應該能夠從那里查詢輸入。 如果您知道文檔不會更改並且總是看起來一樣,則必須專門獲取要查找的輸入框,如下所示
var n = <the n'th input>
var input = iFrame.querySelectorAll('input')[n];
使用查詢選擇器,您可以獲得更具體的信息,並且僅獲取類型為文本的輸入,例如:
var m = <the m'th input where type is text>
var input = iFrame.querySelectorAll('input[type="text"')[m]
然后,當您獲得輸入時,請像這樣更改輸入的值:
input.value = "text here";
編輯
如何使用此示例:
function insertTxt(text) {
/// get the iFrame and then it's 'document'
var iFrame = document.querySelector('#frame1'),
iFrameContent = iframe.contentDocument || iframe.contentWindow.document;
// get the first input box with type text
var input = iFrame.querySelectorAll('input[type="text"')[0]
// set the value of the input field to that text
input.value = text;
}
更改輸入字段很容易。 您現在面臨的問題是“ 跨域策略” 。 如果該iFrame的src不在您嘗試使用此腳本的同一Web域中,那么您將收到錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.