we can create new elements in the list by appending these new elements when
we submit the form.
jqueryprimer/methods.html
$(function(){
$("#task_form").submit(function(event){
event.preventDefault();
varnew_element= $("<li>"+ $("#task").val()+"</li>");
$("#tasks").append(new_element);
});
});
The prepend() method works the same way as the append() method but inserts the
new element before any of the existing ones. The wrap() method wraps the selected
element with the element represented by the jQuery object you specify.
jqueryprimer/methods.html
varwrapper= $("#message").wrap("<divclass='wrapper'></div>").parent();
In this book, we create a few complex structures programmatically using
these techniques.
CSS and Classes
We can use the css() method to define styles on elements, like this:
jqueryprimer/methods.html
$("label").css("color","#f00");
We can define these one at a time, but we can also use a JavaScript hash to
assign many CSS rules to the element:
jqueryprimer/methods.html
$("h1").css({"color":"red",
"text-decoration":"underline"}
);
However, it’s not a good idea to mix style with scripts. We can use jQuery’s
addClass() and removeClass() methods to add and remove classes when certain
events occur. We can then associate styles with these classes. We can combine
jQuery events and classes to change the background on our form fields when
they receive and lose focus.
jqueryprimer/methods.html
$("input").focus(function(event){
$(this).addClass("focused");
});
$("input").blur(function(event){
$(this).removeClass("focused");
});
Appendix 2. jQuery Primer • 266
Download from Wow! eBook <www.wowebook.com> report erratum • discuss