开发者

JQuery / Smarty: variable within .keyUp is undefined

So basically, I'm creating variab开发者_如何学Pythonles within the keyUp method of input box that get their data from a smarty loop (this is within the $(document.ready)

Here is the code

{section name=unitEl loop=$allNavies}
    $("#attack-navy{$allNavies[unitEl].ID}-number").keyup(function(){
        var unit = {$allNavies[unitEl]};
        var element = $("#attack-navy" + unit.ID + "-number");
        var available_count = {$NAVY_{$allNavies[unitEl].ID}_AVAILABLE_COUNT|default:'0'};
        alert(unit.ID);
        // Unit max = available count
        if(element.val() > available_count)
        {
            completeUnitValue(element, available_count);
        }
        // If transport navy: Increase capacity
        if({$allNavies[unitEl].ID} == 16 || {$allNavies[unitEl].ID} == 19 || {$allNavies[unitEl].ID} == 20)
        {
            $("#attack-max-capacity").text(getMaxCapacity());
        }
    });
{/section}

The problem is, when I alert any of the variables (unit, element, available_count) I receive undefined, but when i use the smarty {$allNavies[unitEl]} instead of variables, everything works fine. I just created variables to make the code more readable.

Anyone know why?


I call what you're doing "smarvascript". I loathe it and beg my coworkers to avoid it. But then, I loathe Smarty altogether, so there ya go.

This line:

var unit = {$allNavies[unitEl]};

assigns some PHP value into a JS var.

This line:

alert(unit.ID);

makes it look like you believe 'unit' is an object with properties. You cannot directly assign a PHP object into a JS object and expect it to work...

I'd need to see some of your PHP code and data structures to explain how you should do it, but it is possible that this might help

var unit = {$allNavies[unitEl]|json_encode};

Or, if $allNavies[unitEl] is an array:

var unit = {$allNavies[unitEl]|@json_encode};

I could probably help most if I knew what the structure of $allNavies was.

Also, I am curious...where are your {literal} markings to keep the JS curly braces from making Smarty freak out?

Edit:

Here is a little trick I like to use when I am forced into injecting Smarty into JS:

//{literal}
( function( allNavies )
{
    /*
      allNavies is now a JS object and you can work purely with JS in here
     */
}(
    //{/literal}
    {$allNavies|@json_encode}
    //{literal}
) );
//{/literal}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜