I am creating a jquery function which allows users to create rules and append these rules to a list. I am currently writing the list item html in long form inside the function and it works exactly how it is meant to, but I was wondering if there was a better/more efficient way to create this new list item than writing out all of the html?
Here is the code I currently use:
var li = jQuery('<li>').html('<div id\="rule-desc\">' + desc + '</div>'
+'<input type=\"button\" class=\"remove-rule\" value=\"Remove\" />'
+ '<input type=\"hidden\" name=\"rule['+ index + '][type]" value="' + rule_type + '"/>'
+ '<input type=\"hidden\" name=\"rule['+ index + '][value]" value="' +开发者_JAVA技巧 value + '"/>'
jQuery("#element-rules").append(li);
Thanks for looking.
This looks like a staple case for something like mustache.js or handlerbars.js. If you were using, say, Handlebars, your code would look like this:
// Once, compile the template
var template = '
<div id="rule-desc">{{desc}}</div>
<input type="button" class="remove-rule" value="Remove" />
<input type="hidden" name="rule[{{index}}][type]" value="{{rule_type}}" />
<input type="hidden" name="rule[{{index}}][value]" value="{{value}}" />';
var $ruleset = Handlebars.compile(template);
// Then, whenever you build your rule:
jQuery("#element-rules").append(jQuery("<li>").html($ruleset({
desc: desc,
index: index,
value: value,
rule_type: rule_type
}));
The basic idea is that you build a template, and then generate HTML by passing a hash of properties to the compiled template, from which you get HTML back. It makes large-scale management of this sort of thing quite easy.
The most efficient way would be to just append a string containing the html for the list element to be added. For added speediness, you can store the target element in a variable that is accessible to the function which appends the code. ie:
var list = jQuery("#element-rules");
function addStuff(desc, rule_type, index, value){
list.append(
'<li>'+
'<div id\="rule-desc\">' + desc + '</div>'
+'<input type=\"button\" class=\"remove-rule\" value=\"Remove\" />'
+ '<input type=\"hidden\" name=\"rule['+ index + '][type]" value="' + rule_type + '"/>'
+ '<input type=\"hidden\" name=\"rule['+ index + '][value]" value="' + value + '"/>
'<li>'
);
}
This both most efficiently creates the new jQuery node with the content inside it and does away with the need to look up the element each time you add the new list item to it.
var li=$("<li/>").append(
$("<div/>",{id:"id",}).html(desc).append(
$("input[type="button"]",{class:"remove-rule",value:"Remove"}).append(
$("input[type="hidden"]",{name:"rule",value:rule_type}).append(
$("input[type="hidden"]",{name:"rule",value:value})
); ); );
$("#element-rules").append(li);
i havent tested it but the basic idea is you can use .append()
http://api.jquery.com/append/
http://www.electrictoolbox.com/jquery-append-add-text-to-element/
精彩评论