javascript - Applying function to a single newly created element -
i use each iterate on set of matched selectors, , apply functionality such displaying prompt text in input.
$('.default-value').each(function () { var $t = $(this), default_value = this.value; $t.css('color', '#929292'); $t.focus(function () { if (this.value == default_value) { this.value = ''; $t.css('color', 'black'); } }); $t.blur(function () { if ($.trim(this.value) == '') { $t.css('color', '#929292'); this.value = default_value; } }); }); instead, wish write javascript takes array, creates inputs, , applies same functionality above it. instance, in below script, need add functionality newly created input elements, , rather not use each iterate on them. how can accomplished?
jquery.fn.extend({ dialog_prompt: function(obj) { var dialog=$('div') .append($('input',{type: 'hidden',autofocus: 'autofocus'})); var arraylength = obj.elements.length; (var = 0; < arraylength; i++) { var input=$('input',obj.elements[i].update?{'class': 'update-value'}:{}); //how add .default-value script element? dialog.append(input); } //other script goes here... return this.each(function () { $(this).dialog(obj); }); } }); edit
would following? save default_value?
var input=$('input',obj.elements[i].update?{'class': 'update-value'}:{}) .css('color', '#929292') .focus(function () { if (this.value == default_value) { //where default_value applied this.value = ''; $t.css('color', 'black'); } }) .blur(function () { if ($.trim(this.value) == '') { $t.css('color', '#929292'); this.value = default_value; //where default_value applied } })
from comments, appears you're asking how handle variables inside .each() callback. if declare variable var inside .each() callback function, exist lifetime of specific callback , new variable created each time callback function called. it's normal local variable in function. created , destroyed each time function called:
xxx.each(function() { var temporaryvariable; // survives duration of function call }); if want variable last across .each() callback calls, declare @ higher scope exists across callback calls.
var longerperistingvariable = []; xxx.each(function() { longerpersistingvariable.push("whatever"); }); console.log(longerperistingvariable);
Comments
Post a Comment