使用 ---innerHTML = "...<a href='http://...'>HttpLink</a>..." 在 javascript 函数中创建链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11588460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
create link in javascript function with --- innerHTML = "...<a href='http://...'>HttpLink</a>..."
提问by Rediet
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 编写,但我有一个我无法理解的问题。以下代码适用于其他浏览器,但不适用于 IE9。我知道这与此有关,innerHTML
但我无法理解为此找到的答案。
<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)?
在不改变结构的情况下我应该改变什么(如果可能,只改变内部 HTMl 部分)?
回答by
Since you're creating an a
element, you simply assign the href to the element via the .href
property.
由于您正在创建一个a
元素,您只需通过.href
属性将 href 分配给该元素。
You can set its text content with .innerHTML
as a convenience, though it's not really a "pure" approach.
.innerHTML
为了方便起见,您可以设置其文本内容,尽管它并不是真正的“纯”方法。
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"));
回答by Moin Zaman
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.
您的代码正在原始页面中创建另一个 HTML 页面。那是错误和无效的。这是因为某些浏览器会宽容和纠正您的代码甚至可以工作的事情。
If you're creating a hyperlink element, you should be adding text or an image or other inline elements inside it using innerHTML.
如果您正在创建一个超链接元素,您应该使用innerHTML 在其中添加文本或图像或其他内联元素。
You should change its attribute to set the href with img11.href='http://xyz.com';
你应该改变它的属性来设置href img11.href='http://xyz.com';