简体   繁体   English

MVC部分视图清除脚本Jquery Ajax

[英]MVC Partial View clearing scripts Jquery Ajax

Project: Asp.NET Core 2.1 项目:Asp.NET Core 2.1

Working on a dashboard project that has a side nav that's divides into sub side's etc. On the right side there is a "main view" where the partial should be loaded, so when the partial is selected it should be rendered on the right-hand side. 在仪表板项目上进行操作,该项目的侧面导航分为子侧面,等等。在右侧有一个“主视图”,应在其中加载部分,因此,当选择了部分时,应在右侧显示侧。

I have accomplished all of this, but when I have 2 different views with some javascript that is equal, like a variable, I then get an error for redeclaring, this is because the last script loaded is still cached. 我已经完成了所有这些工作,但是当我有2个不同的视图并且使用了一些相等的javascript(如变量)时,我得到一个重新声明错误,这是因为上次加载的脚本仍在缓存中。 Anyone knows how to attack this problem? 有人知道如何解决这个问题吗?

The variables for the partial are also declared in the file and not separate, have tried to separate also, but this didn't work. 局部变量也已在文件中声明且未分开,也尝试了分开,但这没有用。

Thinking about just not loading this Ajax, but I like the smoothness of it. 考虑不加载此Ajax,但我喜欢它的平滑性。

Example

View1: 视图1:

<div>
  <h1>Hello View1</h1>
  <script>
  const myVar1 = 'Hello';
  </script>
<div>

View2: 视图2:

<div>
  <h6>Hello View2</h6>
  <script>
  const myVar1 = 'Hello';
  </script>
</div>

Error: redeclaration of myVar1. 错误:重新声明了myVar1。

Thanks in advance! 提前致谢!

What you need is a namespace. 您需要的是名称空间。 JavaScript doesn't use the namespace keyword. JavaScript不使用namespace关键字。 What is used instead is closures. 而是使用闭包。 You cannot control the variable names especially when it is not your code. 您不能控制变量名,尤其是当它不是您的代码时。 Try this: 尝试这个:

Example

View1: 视图1:

<div>
    <h1>Hello View1</h1>
    <script>
        var cl1 = (function(e){
            const myVar1 = 'closure 1'; // No public access.
            return {
                myVar1:myVar1, // Assign public access to cl1.myVar1.
                vname:function(){return myVar1; } // or assign it as a getter.
            };
        })();
    </script>
<div>

View2: 视图2:

<div>
    <h6>Hello View2</h6>
    <script>
        var cl2 = (function(){
            const myVar1 = 'closure 2';
            return {
                myVar1:myVar1,
                vname:function(){return myVar1; }
            };
        })();
    </script>
</div>

Test the output: 测试输出:

  <script>
    console.log('cl1.myVar1', cl1.myVar1, cl1.vname());
    console.log('cl2.myVar1', cl2.myVar1, cl2.vname());
  </script>

It results in: 结果是:

cl1.myVar1 closure 1 closure 1
cl2.myVar1 closure 2 closure 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM