admin管理员组

文章数量:1287181

I'm learning to write with html, but I have one problem I cannot understand. The following code works in other browsers but not in IE9. I know it has something to do with innerHTML but I could not understand the answers I found for this.

<html> <head> <script type="text/javascript">
function hw_function1() {
    var img11=document.createElement("a"); 
    img11.innerHTML = "<html> <body> <a href=''>Google</a> </body></html>";
    document.body.appendChild( img11 );
}
</script>
<body>
    <a href="#" onclick="javascript:hw_function1()";>Test</a>
</body> </html>

What should I change WITHOUT changing the structure (only the innerHTMl-part if possible)?

I'm learning to write with html, but I have one problem I cannot understand. The following code works in other browsers but not in IE9. I know it has something to do with innerHTML but I could not understand the answers I found for this.

<html> <head> <script type="text/javascript">
function hw_function1() {
    var img11=document.createElement("a"); 
    img11.innerHTML = "<html> <body> <a href='http://google.de'>Google</a> </body></html>";
    document.body.appendChild( img11 );
}
</script>
<body>
    <a href="#" onclick="javascript:hw_function1()";>Test</a>
</body> </html>

What should I change WITHOUT changing the structure (only the innerHTMl-part if possible)?

Share Improve this question edited Jul 21, 2012 at 16:04 Toon Krijthe 53.4k38 gold badges149 silver badges203 bronze badges asked Jul 21, 2012 at 0:18 RedietRediet 331 gold badge1 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Since you're creating an a element, you simply assign the href to the element via the .href property.

You can set its text content with .innerHTML as a convenience, though it's not really a "pure" approach.

var img11=document.createElement("a");

img11.href='http://google.de';
img11.innerHTML = 'Google';

document.body.appendChild( img11 );

Another way to set the text content would be like this...

img11.appendChild(document.createTextNode("Google"));

You code is creating another HTML page inside the original. That is wrong and invalid. It's because some browsers are forgiving and correcting things that your code even works.

If you're creating a hyperlink element, you should be adding text or an image or other inline elements inside it using innerHTML.

You should change its attribute to set the href with img11.href='http://xyz.';

本文标签: