Create link with JavaScript
I'm trying to generate a link (a-element) with JavaScript, but it just doesn't work. Even though I append the element to the body. Nothing is being displayed. I found various examples, but nothing seems to work.
function getLink(){
var a = document.createElement('a');
a开发者_StackOverflow.title = "text";
a.innerHTML = a.title;
a.href = "http://example.com";
document.body.appendChild(a);
}
Looking at the page you linked us to in comments:
<body onload="getVideo"></body>
getVideo
is not a function call.
Write:
<body onload="getVideo()"></body>
Notice how Vache posted a testcase containing the snippet you gave us, and was able to immediately prove that the function getVideo
works. Then all it took was finding what other Javascript was involved, and that was just eight characters, leading to this solution. Basic debugging!
Further thoughts collated from around the question:
innerText
would be more appropriate thaninnerHTML
; conceptually you're defining what the user should see, not what markup should produce it. Because of this,innerText
will also escape HTML entities for you.getVideo
is a poor name for a function that does not "get" anything at all.
If the code you've provided is all that's being run, nothing will happen.
You haven't explicitly called the function getLink
.
Adding:
getLink();
the line after your ending curly brace runs successfully.
Try putting a div on the page, and add the link to the div. Also, try using innerText instead of innerHTML.
var div = document.getElementById("div1");
if (div)
{
var a = document.createElement('a');
a.title = "text";
a.innerText = a.title;
a.href = "http://example.com";
div.appendChild(a);
}
精彩评论