简体   繁体   English

使用 javascript 更改 HTML object 的 innerHTML

[英]Changing the innerHTML of an HTML object with javascript

I am loading an external page into an HTML object:我正在将外部页面加载到 HTML object 中:

var object = document.createElement('object')
object.data = 'myPage.html'
$("#myDiv").html(object)

Now I want to modify the source of object .现在我想修改object的来源。 But I can't figure out how to use jQuery to access any of the elements of myPage.html .但我不知道如何使用 jQuery 访问myPage.html的任何元素。 For example:例如:

$("#myPageDiv").css('background-color', '#000');

has no effect.没有效果。 How can I modify the elements within the injected HTML object?如何修改注入的 HTML object 中的元素?

The innerHTML of an object is fallback content . object 的innerHTML后备内容

It is to be displayed if the external resource the object is loading isn't supported.不支持object加载的外部资源时显示。

Assigning an HTML document's URL to data is effectively using the object as an <iframe> .将 HTML 文档的 URL 分配给data有效地将 object 用作<iframe> You should probably use an iframe instead as they have been consistently supported among browsers for much longer.您可能应该使用 iframe 代替,因为它们在浏览器中得到一致支持的时间要长得多。

Once you recognise you are dealing with a frame, you can find plenty of information on how to access the content.一旦你意识到你正在处理一个框架,你就可以找到大量关于如何访问内容的信息。

You ask " how to use jQuery to access any of the elements of myPage.html"您问“如何使用 jQuery 访问 myPage.html 的任何元素”

 var object = document.createElement('object') object.d = '<div id="x">XXX</div>' $("#my").html(object.d); $('#x').text("<b>Some</b> new text.");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="my">ddd</div>

Try this尝试这个

var object = document.createElement('object')
object.d = '<div id="x">XXX</div>'
$("#my").html(object.d);
$('#x').text("<b>Some</b> new text.");

The Jquery's load method and css method should be able to do the trick. Jquery 的load方法和css方法应该可以解决问题。

Hence, please try this (for demonstration purpose):因此,请尝试这个(用于演示目的):

HTML (eg main.html ) HTML(例如main.html

  src="https://code.jquery.com/jquery-3.5.1.js"
  integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
  crossorigin="anonymous"></script>

<input type=button onclick="javascript:step1();" value="(Step 1) Load HTML">

<div id=myDiv></div>


<input type=button onclick="javascript:step2();" value="(Step 2) Change color">


<script>

function step1()
{
$("#myDiv").load('myPage.html');
}

function step2()
{
$("#myPageDiv").css('background-color', '#000');

}

</script>

and for the myPage.html对于myPage.html

This is a test
<br>
<div id=myPageDiv>NEED TO CHANGE BACKGROUND COLOR</div>

You may see a fully working HTML here:您可能会在这里看到一个完全正常工作的 HTML:

http://www.createchhk.com/so_Jan05.html http://www.createchhk.com/so_Jan05.html

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

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