Javascript function inside jQuery template is not working correctly
I'm trying to build a list of checkboxes by using jQuery.tmpl It'll list an array of items with a checkbox near them, and I want to check some of these checkboxes parametrically...
The template code is:
<ul>
{{each(i,val) Values}}
<li>
<input type="checkbox" {{if $.inArray(i, Default) != -1}} checked="checked"{{/if}}>
开发者_如何学Go <em>${val}</em>
</li>
{{/each}}
</ul>
and the template definition:
<script type="text/javascript">
$(document).ready(function() {
$('#tpl_selector').tmpl({
Default: [1,2],
Values: {
1: 'Item 1',
2: 'Item 2',
3: 'Item 3'
}
}).appendTo('#area');
});
</script>
So the Item 1 and Item 2 should be checked in this case. The list is created with no problem, but {{if $.inArray(i, Default) != -1}} checked="checked"{{/if}}
part is not working.
However, when I replace 'i' with a number, it works:
{{if $.inArray(1, Default) != -1}} checked="checked"{{/if}}
I doesn't make any sense at all... Do you have any suggestions?
Another logic to fill the checkboxes is ok too, like I don't know smt. like a callback function after the rendering completes or else...
The problem
In JavaScript objects, the key is always a string. Your Default
array contains numbers, but the "needle" you're passing in (i
) is a string, so $.inArray
will always return false
,.
jsfiddle 0
The solutions
Any one of these will work:
- Make
Values
a proper array, rather than an object "indexed" by strings containing numbers.- jsfiddle 1 (Note the zero-based indexing!)
- Make
Defaults
an array of strings.- jsfiddle 2
parseInt()
theValues
key (i
) when you pass it to$.inArray()
. I think this is an ugly fix.- jsfiddle 3
Oh, and welcome to Stack Overflow!
精彩评论