and I go ...">

Why did jquery accidentally crash?

I use jquery to add items to an empty list.

on the page that I have:

<ul id="myList">
</ul>

and I go through such a loop in a script that is called from a dynamically created event handler. (He is the "onDrop" of a list item sorted using a drag and drop operation)

var myListItemHTML;
for (var i = 0 ; i < 5 ; i++)
{
  myListItemHTML += '<li id=listItem'+i+'>This is item number'+i+'</li>';
}

$('#myList').append(myListItemHTML);

and if I check after ...

if ($('#myList li').length == 0 )
{
  alert('Going to crash now since I'm expecting list items')
}

in about 95% of cases when the list is populated, but in about 5% of cases, I hit my warning to cause an exception later.

Has anyone come across this? Is there a callback or a way to find out when / if the application really happens?

+3
source share
4 answers
var myListItemHTML;
for (var i = 0 ; i < 5 ; i++)
{
  $('#myList').append('<li id=listItem'+i+'>This is item number'+i+'</li>');
}

Try just adding inside the for loop.

if ($('#myList li').length == 0 )
{
  alert('Going to crash now since I\'m expecting list items')
}

\ ', .

edit: jsfiddle, "undefined" http://jsfiddle.net/gyEre/1/

+1

, , , . :

, , Chrome, , , .

, , , Chrome JavaScript AJAX, .

, AJAX A, AJAX B. Chrome , B A, .

, , , AJAX , . : http://api.jquery.com/jQuery.ajaxSetup/

, , . !

+1

, , jquery DOM, . -, , , :

addListItem = function (itemID, itemText)
{
   var li = document.createElement('li'); 
   li.setAttribute("id", itemID);

   var liText = document.createTextNode(itemText);
   li.appendChild(goalTextNode);

   document.getElementById('myList').appendChild(li); 

}

for (var i = 0 ; i < 5 ; i++)
{
  addListItem('listItem'+i, 'Item Text'+i);
}

100% .

+1

, script, preend -tag, , script DOM.

, javascript .

+1
source

Source: https://habr.com/ru/post/1787842/


All Articles