...

View Full Version : Display HTML in Javascript



hiyatran
05-21-2012, 10:28 PM
I'm trying to display the elements in an array but doesn't seem to work:


var myurl=new Array("google.com", "yahoo.com");

for (i=0;i<=myurl.length-1;i++){
document.writeln("<a href='http://www.' + myurl[i] + target='_blank'>");
}


Not sure why it is not working??

DaveyErwin
05-21-2012, 10:47 PM
<!DOCTYPE html>
<head>

</head>

<body>
<script type="text/javascript">
var myurl=new Array("google.com", "yahoo.com");

for (i=0;i<=myurl.length-1;i++){
document.writeln("<a href='http://www." + myurl[i] + "' target='_blank'>"+ myurl[i] + "</a>");
}

</script>

</body>
</html>

Old Pedant
05-21-2012, 10:49 PM
In JavaScript--and indeed in virtually every computer language out there--a string starts with " and ends with the next ".

So you have ONLY A SINGLE STRING THERE!



"<a href='http://www.' + myurl[i] + target='_blank'>"

JavaScript WILL NOT inject stuff into the middle or a string. Period. (Unlike PHP.)

Also, since you really ought to be using "..." around HTML attributes.

So:


var myurl=new Array("google.com", "yahoo.com");

for (i=0;i<=myurl.length-1;i++){
var url = myurl[i];
document.writeln('<a href="http://www.' + url + '" target="_blank">' + url + '</a>');
}


HOWEVER... If at all possible, you should *NOT* be using document.write. It's way way obsolescent.

***********

EDIT: Ehhh...too slow again. Well, you can see we basically agree. But I would definitely swap your usage of ' and ".

Taro
05-21-2012, 11:06 PM
Hello,

Here is a script that I have reconfigured with from a personal template, and was originally an OnClick event. This may not work for an external JavaScript file.




function sb()
{
var foo = "Google Site";
var foob = "Yahoo Site";
var TB = document.getElementById('myDiv');
var VB = document.getElementById('myDiv2');
if (TB)
{
TB.innerHTML = (foo.link("http://www.google.com"));
}
if (VB)
{
VB.innerHTML = (foob.link("http://www.yahoo.com"));
}
}//end of function


Hope this helps. Of course, there are improvements to make the code simpler and more efficient. As you can see, the link() function was used, a way to link targets in JavaScript. Getting the element by the ID using inner HTML is a more formidable way than using document.write().

Old Pedant
05-21-2012, 11:51 PM
That code only works if you *ALREADY* have <div>s set up to hold the links.
Better:


<!DOCTYPE html>
<html>
<body>
<div id="putLinksHere"></div>

<script type="text/javascript">
var urls = [ "google.com","yahoo.com","bing.com"];
var here = document.getElementById("putLinksHere");
for ( var u = 0; u < urls.length; ++u )
{
var link = document.createElement("a");
link.href = "http://www." + urls[u];
link.appendChild( document.createTextNode( urls[u] ) );
here.appendChild(link);
}
</script>
</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum