开发者

Javascript function inside jQuery template is not working correctly

开发者 https://www.devze.com 2023-01-24 04:36 出处:网络
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...

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:

  1. Make Values a proper array, rather than an object "indexed" by strings containing numbers.
    • jsfiddle 1 (Note the zero-based indexing!)
  2. Make Defaults an array of strings.
    • jsfiddle 2
  3. parseInt() the Values key (i) when you pass it to $.inArray(). I think this is an ugly fix.
    • jsfiddle 3

Oh, and welcome to Stack Overflow!

0

精彩评论

暂无评论...
验证码 换一张
取 消