jquery - click function to add element and update html -
if have array of table list items:
<div id="target"> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> </ul> </div> and want construct click function adds 'li' , increments inner html of each item, can write:
var listitems = $('#target ul li'); var newitem = document.createelement('li'); newitem.innerhtml = "list item " + (parseint(listitems.size()) + 1); $("#target").click(function() { var list = $('#target ul'); list.append(newitem); }); which works, once. why won't add list item every time click it?
simple fix... should create element inside event listener:
var list = $('#target ul'); $("#target").click(function() { var newitem = document.createelement('li'); newitem.innerhtml = "list item " + (list.find("li").length + 1); list.append(newitem); }); note: i've replaced .size() .length. it's faster , exact same thing :)
Comments
Post a Comment