简体   繁体   English

Javascript:通过ID更新元素?

[英]Javascript: Updating an element by ID?

I'm trying to get an element by ID and update it but I seem to be having trouble since I'm fairly new with javascript. 我正在尝试通过ID获取元素并对其进行更新,但是由于我对javascript很陌生,因此似乎遇到了麻烦。 This is my form: 这是我的表格:

<div class="formRow billingForm">
    <div class="formLabel">First Name</div>
    <div class="formField">
      <input type="text" class="formTextField firstName" value="" name="firstName" maxlength="35" id="firstName">
    </div>
    <div class="formExtraInfo formExtraInfoTall">Enter your name.</div>
  </div>

I'm trying to update the value of the "firstname" by doing the following" 我正在尝试通过执行以下操作来更新“名字”的值:

document.getElementById("firstName").value = "UPDATED";

and it works, but when I try it on my actual site I get null for element even though it's there. 并且它可以工作,但是当我在实际站点上尝试时,即使元素存在,我也无法获得null值。 The whole form is inside an iframe though. 整个表单虽然位于iframe中。

You can't access the content of the iframe with a script from outside of it -- that would introduce XSS vulnerabilities. 您无法从外部使用脚本访问iframe的内容-这会引入XSS漏洞。 You need to somehow load that script inside the iframe or avoid using an iframe at all. 您需要以某种方式将脚本加载到iframe中,或者完全避免使用iframe。 Take a look at this page on same origin policy for information on why that isn't working. 请查看此页面上的同一来源政策,以获取有关为何无效的信息。

try 尝试

      iframe =  getElementByTagName('iframe').contentWindow.document
      iframe.getElementById('firstName').value = 'UPDATED'

When you invoke an iframe you also invoke another HTML page. 调用iframe时,您还会调用另一个HTML页面。 You have to do the scripting inside this iframe's target page. 您必须在此iframe的目标页面中执行脚本。

Make sure the domain URL of the parent page and iframe page is the same then it is possible. 确保父页面和iframe页面的域URL 相同,然后才可以。 This is the JS of the parent to access the form inside. 这是父级的JS,用于访问其中的表单。

var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
innerDoc.getElementById("firstName").value = "UPDATED";

Hope it helps :) 希望能帮助到你 :)

If form is inside the iframe and you are updating the value of form element from the parent of iframe please use the below: 如果form在iframe中,并且您要从iframe的父级更新form元素的值,请使用以下代码:

Assign the value to name of form like below: 将值分配给表单名称,如下所示:

<iframe src="formPage.html" onload="loaded()" name="myFrame" />

and give the id to the form element for example "myForm" 并将id赋予表单元素,例如“ myForm”

Access the element of form inside the the iframe: 访问iframe中的form元素:

myFrame.document.getElementById("myForm").firstName.value = 'UPDATED';

Also make sure your script runs after the iframe is loaded. 另外,请确保您的脚本在iframe加载后运行。 Your iframe tag has an onload event that you can use to determine when the page within the frame is loaded. 您的iframe标记具有一个onload事件,您可以使用该事件确定何时加载框架中的页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM