简体   繁体   中英

Javascript code doesn't load the page

I have a little problem with this javascript code, when I add more site on the list, the page doesn't load. I have to add more than 200 site.

I'm a noob with javascript. Can someone explain what is the problem, what

I'm doing wrong?

 <script language="JavaScript" type="text/javascript">
var a = new Array(
'notiziepericolose.blogspot.it',
'ilcorrieredellanotte.it',                                       
'ilmattoquotidiano.it',
'ilfattonequotidiano.com',
'rebubblica.altervista.org',
'coriere.net'

);
var aa = a.slice();
aa.sort();
document.write("<ol>");
document.write("<b>");
for (i = 0; i < a.length; i=i+1) {
document.write('<li id="demo'+i+'">'+a[i]+'</li>');
}
document.write("</b>");
document.write("</ol>");
</script>

If you're using an Array, you can use a forEach instead of a loop.

 var domUpdate = ''; var websites = ['notiziepericolose.blogspot.it','ilcorrieredellanotte.it','ilmattoquotidiano.it','ilfattonequotidiano.com','rebubblica.altervista.org','coriere.net']; websites.forEach(function(website, index){ domUpdate += '<li id="website-' + ( index + 1 ) + '"><b>' + website + '</b></li>'; }); document.getElementById('hook').innerHTML = '<ol>' + domUpdate + '</ol>'; 
 <div id="hook"></div> 

if ES6 is possible for you, you can do it like this:

 var a = new Array( 'notiziepericolose.blogspot.it', 'ilcorrieredellanotte.it', 'ilmattoquotidiano.it', 'ilfattonequotidiano.com', 'rebubblica.altervista.org', 'coriere.net'); var aa = a.slice(); var mL = document.getElementById('mylist'); aa.sort().map(el => { var li = document.createElement("li"); var b = document.createElement("b"); var t = document.createTextNode(el); b.appendChild(t); li.appendChild(b); mL.appendChild(li); }); 
 <ol id="mylist"></ol> 

I'm thinking document.write is the wrong choice here, as it seems to be clearing the document. https://developer.mozilla.org/en-US/docs/Web/API/Document/write Probably you want to bind the new content to existing html through document.getElementById or something like that

I guess the first thing is that document.write is very rarely used now as there a better and more efficient ways of adding things (elements, text etc) to the DOM (more on that later). In addition, in your case, what you don't realise is that document.write is not like echo or println ; each time it is used it clears the document, which is probably why you're not seeing anything appear. In other words, The results of multiple document.write s are not cumulative .

The second thing is that there are better ways of "labelling" elements than with id s, particularly if there are a lot of them on the page like you'll have. Again, there are now much better ways of targetting elements, or catching events than there were ten or fifteen years ago.

So, let's talk about your code.

You can quickly create a array using the [] brackets.

var arr = [
  'notiziepericolose.blogspot.it',
  'ilcorrieredellanotte.it',
  'ilmattoquotidiano.it',
  'ilfattonequotidiano.com',
  'rebubblica.altervista.org',
  'coriere.net'
];

You don't have to create a copy of the array in order to sort it - it can be done in place:

arr.sort();

I'm going to keep your loop but show you a different way of concatenating strings together. Some people prefer adding strings together, but I prefer this way, and that's to create an array of the little parts of your string and then join() them together**.

// Set l as the length, and create an output array called list
for (var i = 0, l = arr.length, list = []; i < l; i++) {

  // I've changed things here. I've added a class called item
  // but also changed the element id to a data-id instead
  var li = ['<li class="item" data-id="', i, '">', arr[i], '</li>'];

  // Push the joined li array of strings into list
  list.push(li.join(''));
}

Assuming you have an element on your page called "main":

HTML

<div id="main"></div>

JS

You can add the list array as an HTML string to main by using [ insertAdjacentHTML ] method:

var main = document.getElementById('main');

// Note that I've given the ordered list an id called list
var HTML = ['<ol id="list"><b>', list.join(''), '</b></ol>'].join('');
main.insertAdjacentHTML('beforeend', html);

OK, so that's pretty easy. But I bet you're asking how you can target the individual items in the list so that if I click on one of them it alerts what it is (or something).

Instead of adding an event listener to each list item (which we could but it can work out performatively expensive the more items you have), we're going to attach one to the ol element we added that list id to and catch events from the items as they bubble up:

var ol = document.getElementById('list');

Then an event listener is added to the list that tells us what function ( checkItem ) is called when a click event is raised:

ol.addEventListener('click', checkItem);

Our function uses the event ( e ) to find out what the event's target was (what item was clicked), and alerts its text content.

function checkItem(e) {
  alert(e.target.textContent);
}

You can see all this working in this demo . Hope some of this was of some help.

** Here's another way of sorting, and looping through the array using reduce :

var list = arr.sort().reduce(function (p, c, i) {
  return p.concat(['<li class="item" data-id="', i, '">', c, '</li>']);
}, []).join('');

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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