How to write in JQuery function which return new div?
How to write in JQuery function which return new div ? ( I get like parameter to function some object, base on that object and properties I need to return different color and text in div. Example: if I got F I paint red and write "fire", if I got W I paint blue and write "watter开发者_C百科" ). Can anybody help
function getADiv() {
return $('<div/>', {
text: 'hello',
color: 'red'
});
}
Hmmm something like that ?
function makeDiv(type){
var params;
if(type == "F"){
params = {text: "fire", color: "red"};
}
else if(type == "W"){
params = {text: "water", color: "blue"};
}
else return null;
return $("<div>")
.text(params.text)
.css("color", params.color);
}
My take:
var newDiv = function(options){
var html = '<div class="';
if(options.color == 'R')
html += 'rubyred';
html += '">Element: ' + options.element + '</div>';
return $(html);
};
var myNewDiv = newDiv({ color: 'R', element: 'fire' });
Or, simpler (not as fancy):
var newDiv = function(letter){
var $d = $('<div>');
if(letter == 'F')
$d.html('fire').css('color', 'red');
else if(letter == 'W')
$d.html('water').css('color', 'blue');
return $d;
};
var waterDiv = newDiv('W');
This should do it:
function createDiv(type) {
switch (type.toLowerCase()) {
case 'f':
return $('<div>').css({ color: 'red' }).text('Fire');
break;
case 'w':
return $('<div>').css({ color: 'blue' }).text('Water');
break;
}
}
Live example here.
精彩评论