how does the first part of this work?
I have this snippet of jquery and i want to know how it works....i understand the keypup but what i dont understand is the data ..what is it doing and
here is the parts i dont understand
$('p span').each(function(){
$(t开发者_如何转开发his).data('factor',$(this).text());
})
and
$('p span').each(function(){
$(this).text(function(){
return $(this).data('factor') * factor;
});
})
seems like they are looping but for what
jQuery's data function attaches a piece of data to an element. In the first block, you are looping through the spans, and adding a piece of data called 'factor' to each one, and the data is the span's text. In the second block, you are setting each span's text to the original 'factor' value saved times the value of a factor
variable.
it saves the original values of the spans in the 1st part:
$('p span').each(function(){
$(this).data('factor',$(this).text());
})
and then whenever the input is changed, it takes the number inputed times the individual spans 'factor' that was set on start.
if you want more explanation of $(this).data
... look here
The $.fn.data function for jquery basically attaches object specific data to the element. It's almost the same as having something like this:
<span data-factor="something">Text</span>
If you called that method on this element you would get:
var text = $('span').data('factor');
// text is "something"
精彩评论