在Javascript中分配变量

时间:2017-03-14 21:13:27

标签: javascript jquery html node.js

我已将索引定义为do.call(rbind, res1) 这是HTML主体的顶部,因此我可以将其作为全局变量使用。 我想将<%var index = 0;%>的值分配给$(this).val()。 我已多次尝试但无法弄明白。 我在后端使用Node.js,在前端使用EJS。

<% index %>

2 个答案:

答案 0 :(得分:2)

正如有人提到的,您需要区分服务器上计算的内容和浏览器上的内容:

常见页面可能如下所示:

<script>
    var index = <% index_calculated_on_server %>;
    $("#agency").on("change", function () {
        var $modal = $('#myModal');
            if($(this).val() !== '0'){
                index = parseInt($(this).val()); ????
            }
            $modal.modal('show');
        }
    });
</script>

答案 1 :(得分:1)

您的问题在于混合服务器端和客户端呈现。为了说明,我们来看看你提供的代码片段。

<script>
    $("#agency").on("change", function () {
        var $modal = $('#myModal');
            if($(this).val() !== '0'){
                <% index %> = parseInt($(this).val()); // This is the problem line
            }
            $modal.modal('show');
        }
    });
</script>

EJS在被发送到客户端之前被渲染,合并提供给它的变量,因此如果你将index设置为零,你将在渲染完成后得到这样的代码片段。

<script>
    $("#agency").on("change", function () {
        var $modal = $('#myModal');
            if($(this).val() !== '0'){
                0 = parseInt($(this).val()); // Can't assign zero. 
            }
            $modal.modal('show');
        }
    });
</script>

相反,你应该做的是将你的<% index %>包装在一个包装元素中,这应该允许你在客户端操作它。

$("#agency").on("change", function () {
    var $modal = $('#myModal');
    if( $(this).val() !== '0' ) {
        $(".index-counter").text(parseInt($(this).val()));
    }
    $modal.modal = function () { /* stub function */ };
    $modal.modal('show');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="agency" id="agency" />

<!-- This would be where <% index %> was inserted -->
<div class="index-counter">0</div>